Leetcode题库——20.有效的括号


@author: ZZQ
@software: PyCharm
@file: IsValid.py
@time: 2018/9/16 20:20
要求: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
1)左括号必须用相同类型的右括号闭合。
2)左括号必须以正确的顺序闭合。

class Solution():
    def __init__(self):
        pass

    def isCouple(self, str1, str2):
        if str1 == '(' and str2 == ')':
            return True
        else:
            if str1 == '[' and str2 == ']':
                return True
            else:
                if str1 == '{' and str2 == '}':
                    return True
                else:
                    return False

    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        length = len(s)
        for i in range(0, length):
            if s[i] == '(' or s[i] == '[' or s[i] == '{':
                stack.append(s[i])
                if len(stack) == length:
                    return False
            else:
                if len(stack) == 0:
                    return False
                flag = self.isCouple(stack[-1], s[i])
                if flag:
                    stack.pop(-1)
                else:
                    return False
        if len(stack) != 0:
            return False
        return True

    def isValid2(self, s):
        a = {')': '(', ']': '[', '}': '{'}
        l = [None]
        for i in s:
            if i in a and a[i] == l[-1]:
                l.pop()
            else:
                l.append(i)
            print(l)
        return len(l) == 1  # 最终要保证栈中的元素为空


if __name__ == "__main__":
    str = "()[]{}"
    # str = "(]"
    # str = "([)]"
    # str = "{[]}"
    str = "([]"
    answer = Solution()
    print(answer.isValid2(str))
posted @ 2018-09-18 20:48  恩zzq我是  阅读(142)  评论(0编辑  收藏  举报