zoukankan      html  css  js  c++  java
  • 赏月斋源码共享计划 第七期 括号匹配

    题目:

    字符串中有括号”()[]{}”,设计算法,判断该字符串是否有效
    括号必须以正确的顺序配对,如:“()”、“()[]”是有效的,但“([)]”无效

    解法一:

    # coding=utf-8
    from pythonds.basic.stack import Stack # 栈可以不用此包,入栈append,出栈pop
    
    def parChecker(symbolString):
        s = Stack()
        balanced = True
        symbolList = list(symbolString)
        index = 0
        while balanced == True and index < len(symbolString):
            if symbolString[index] == "(":
                s.push(symbolString[index])
            else:       # symbolString=")"
                if s.isEmpty():
                    balanced = False
                else:
                    s.pop()
            index += 1
    
        if s.isEmpty():
            balanced = True
        else:
            balanced = False
    
        # for i in symbolList:
        #     if i == '(':
        #         s.push(i)
        #     else:     # i == ')'
        #         if s.isEmpty():
        #             balanced = False
        #         else:
        #             s.pop()   
        # if s.isEmpty():
        #     balanced = True
        # else:
        #     balanced = False
    
        return balanced
    
    if __name__ == "__main__":
        symbolString = '(())()()()((()()(()())))('
        print(parChecker(symbolString))
    

      

    解法二(更好):(来自https://blog.csdn.net/weixin_42018258/article/details/80579081)

    def match_parentheses(s):
        # 把一个list当做栈使用
        ls = []
        parentheses = "()[]{}"
        for i in range(len(s)):
            si = s[i]
            # 如果不是括号则继续
            if parentheses.find(si) == -1:
                continue
            # 左括号入栈
            if si == '(' or si == '[' or si == '{':
                ls.append(si)
                continue
            if len(ls) == 0:
                return False
            # 出栈比较是否匹配
            p = ls.pop()
            if (p == '(' and si == ')') or (p == '[' and si == ']') or (p == '{' and si == '}'):
                continue
            else:
                return False
    
        if len(ls) > 0:
            return False
        return True
    
    
    if __name__ == '__main__':
        s = "{abc}{de}(f)[(g)"
        result = match_parentheses(s)
        print(s, result)
        s = "0{abc}{de}(f)[(g)]9"
        result = match_parentheses(s)
        print(s, result)
    

      

  • 相关阅读:
    node vue 项目部署问题汇总
    Java删除空字符:Java8 & Java11
    moco固定QPS接口升级补偿机制
    Selenium4 IDE特性:无代码趋势和SIDE Runner
    JsonPath工具类单元测试
    Mac上测试Internet Explorer的N种方法
    JsonPath工具类封装
    Selenium4 IDE,它终于来了
    质量保障的方法和实践
    JsonPath实践(六)
  • 原文地址:https://www.cnblogs.com/sddai/p/13931209.html
Copyright © 2011-2022 走看看