163-20. 有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。(第一个是错误的,第二个是我写的,我对栈的理解有偏差,所以在写第三种的时候出了些问题:我理解的是一次性将所有的字符串都压入栈中,而事实上却是每次只压入一个元素入栈,看来我还得补补课.)
class Solution(object):
    rule_dict = {"(": ")", "{": "}", "[": "]"}

    def isValid1(self, s):
        """我很遗憾,这是一个错误的方式
        :type s: str
        :rtype: bool
        """
        if len(s) & 1 != 0:
            return False
        left = 0
        right = len(s) - 1
        while left < right:
            if self.rule_dict.get(s[left], "") == s[left+1]:
                left += 2
                continue
            if self.rule_dict.get(s[right-1], "") == s[right]:
                right -= 2
                continue
            if self.rule_dict.get(s[left], "") != s[right]:
                return False
            left += 1
            right -= 1
        return True

    def isValid2(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) & 1 != 0:
            return False

        for i in range(len(s)//2+1):
            s = s.replace("()", "")
            s = s.replace("[]", "")
            s = s.replace("{}", "")

        return not s

    rule_dict3 = {")": "(", "}": "{", "]": "["}
    def isValid4(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        for c in s:
            if c in ("(", "[", "{"):
                stack.append(c)
            elif c in (")", "]", "}"):
                if not stack or self.rule_dict3[c] != stack[-1]:
                    return False
                stack.pop()
        return not len(stack)

    def isValid5(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dic = {'{': '}',  '[': ']', '(': ')', '?': '?'}
        stack = ['?']
        for c in s:
            if c in dic: stack.append(c)
            elif dic[stack.pop()] != c: return False
        return len(stack) == 1


if __name__ == '__main__':
    s = "[({(())}[()])]"
    s1 = Solution()
    root = s1.isValid(s)
    print(root)

原文地址:https://www.cnblogs.com/liuzhanghao/p/14355393.html