20.leetcode 有效的括号(简单)

leetcode python 刷题记录,从易到难

一、题目

在这里插入图片描述在这里插入图片描述

二、解答

1.思路

对输入参数做判断

  1. 字符串长度为奇数直接返回False
  2. 字符串为空字符串,返回True

处理逻辑

  1. 定义一个映射方便根据左括号找到右括号
  2. 定义一个list作为栈
  3. 遍历字符串的每个字符
  4. 如果是左括号就放入栈
  5. 如果是右括号则与弹出的栈顶元素比对
  6. 如果不是一对,就返回False
  7. 遍历完字符串后,如果栈的长度为0,返回True,不等于零则返回False

2.实现

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) %2 !=0:
            return False
        if len(s) =="":
            return True
        char_map = {
    
    "[":"]","{":"}","(":")"}
        stack = []
        for c in s:
            if c in char_map:
                stack.append(c)
            else:
                if len(stack)>0:
                    if char_map[stack.pop()] != c:
                        return False
        return len(stack)==0

3.提交结果

在这里插入图片描述

三、Github地址

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/20.py

参考链接

https://leetcode-cn.com/

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/107599902