zoukankan      html  css  js  c++  java
  • 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)
    
    
  • 相关阅读:
    neo4j命令
    prometheus使用四(alertmanager&grafana告警及服务发现)
    prometheus使用三(自定义监控指标实现)
    prometheus使用二(export与grafana接入)
    prometheus使用一
    一次修改域名解析引发的问题
    微信小程序支付,看这一篇就够了
    常用命令
    常见报错与问题注意
    redis迁移复制数据,主从关系建立实践
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14355393.html
Copyright © 2011-2022 走看看