leetcode 每日一题 20. 有效的括号

思路:

由于括号一般是成对出现,可以利用栈后进先出的特征。将字符串字符按顺序压入栈中,压入过程中如果遇到右括号时,推出栈顶元素,判断当前要压入的右括号是否和栈顶元素是一对,如果是则继续下一字符的压入判断操作。如果不是,直接返回False。当压入过程结束后,如果栈内为空则返回True,否则返回False。

例如:

  {  [  (  )  ]  (  )  }  (  )

 

代码:

class Solution(object):
    def isValid(self, s):
        stack = []
        mapping = {")": "(", "}": "{", "]": "["}
        for char in s:
            if char in mapping:
                top_element = stack.pop() if stack else '#'
                if mapping[char] != top_element:
                    return False
            else:
                stack.append(char)
        return not stack

 

 

posted @ 2020-05-02 13:11  nil_f  阅读(97)  评论(0)    收藏  举报