Leetcode20. 有效的括号

题目描述:

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

括号必须以正确的顺序关闭,"()" 和 "()[]{}" 是有效的但是 "(]" 和 "([)]" 不是。

解题思路:

利用栈的先入后出的原理,将对应的字符[ '[' , '(' , '{' ]入栈,每出现一个[ ')' , '}' , ']']的字符,将栈中的字符pop出来然后连接后进行判断,是正确的顺序的话就继续遍历字符串,直到结束。

代码:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        stack
        """
        x = ['(','[','{']
        y = [')','}',']']
        z = ['()','{}','[]']
        res = []  # stack
        for i in s:
            if i in x:  # ( [ {
                res.append(i)
            if i in y:  # ) ] }
                if res == []:
                    return False
                sz = res.pop() + i
                if sz not in z:
                    return False
        if res != []:
            return False
        return True       


猜你喜欢

转载自blog.csdn.net/sinat_24648637/article/details/79804204