LeetCode-20. 有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
class Solution:
    def isValid(self, s: str) -> bool:
        temp = [0]
        if len(s)%2 == 1:
            return False
        for c in s:
            if c == '(' or c == '[' or c == '{':
                temp.append(c)
            elif c == ')' and temp[len(temp)-1] == '(':
                del temp[len(temp)-1]
            elif c == ']' and temp[len(temp)-1] == '[':
                del temp[len(temp)-1]
            elif c == '}' and temp[len(temp)-1] == '{':
                del temp[len(temp)-1]
            else:
                return False
        if len(temp) == 1:
            return True
        else:
            return False
posted @ 2021-07-15 16:29  小Aer  阅读(2)  评论(0编辑  收藏  举报  来源