20. 有效的括号

leetcode

代码随想录 思路:分析不匹配的情况,生成

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        d = {
            "(": ")",
            "{": "}",
            "[": "]"
        }
        for item in s:
            if item in d:
                stack.append(d[item])
            elif not stack or stack.pop() != item:
                return False
        
        return len(stack) == 0

时间复杂度:O(n)