[LeetCode]20. Valid Parentheses

20. Valid Parentheses

思路:有效的括号

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        for x in s:
            if x in '})]':
                if not stack:
                    return False
                if x == '}':
                    val = stack.pop()
                    if val != '{':
                        return False
                elif x == ')':
                    val = stack.pop()
                    if val != '(':
                        return False
                else:
                    val = stack.pop()
                    if val != '[':
                        return False
            else:
                stack.append(x)
        return len(stack) == 0

简化代码:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        closeB = set(')}]')
        openB = {'(':')', '{':'}', '[':']'}
        for c in s:
            if c in closeB:
                if not stack:
                    return False;
                temp = stack.pop()
                if openB[temp] != c:
                    return False
            else:
                stack.append(c)
        if stack:
            return False
        return True
posted @ 2017-09-06 19:19  banananana  阅读(121)  评论(0编辑  收藏  举报