有效的括号

2018-12-07  本文已影响0人  Challis

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

核心思想:通过列表模拟stack对数据进行操作,当是左边的符号进行入栈操作,是右边的符号,进行出栈操作。最后循环完成,看栈是否为空。

def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        left = '({['
        right = ')}]'
        lst = []    # 使用列表模拟队列
        if len(s) == 0:
            return True
        if len(s) % 2:    # 判断长度是奇数返回错误
            return False
        for i in s:
            if i in left:
                lst.append(i)
            elif i in right:  
                if len(lst) == 0:
                    return False
                else:
                    pop_value = lst[-1]
                    lst.pop()
                    if left.index(pop_value) == right.index(i):   # 比较两者的是否对应。
                        pass
                    else:
                        return False
        if len(lst) > 0:
            return False
        else:        # 所有的匹配完成才返回正确。
            return True
上一篇 下一篇

猜你喜欢

热点阅读