20. Valid Parentheses

要依序判断已经遍历过的括号的开闭状态,可以用stack,遇到对不上的直接 False。遍历完了还有没关上的括号也直接 False.

懒得写状态函数了,反正就三个,直接dict解决。

class Solution:
    def isValid(self, s: str) -> bool:
        n = len(s)
        pairs = {'(':')', '[':']', '{':'}'}
        stack = []
        for i in range(n):
            if s[i] in pairs:
                stack.append(s[i])
            else:
                if not stack or pairs[stack.pop()] != s[i]: 
                    return False
        return True if not stack else False

Last updated

Was this helpful?