Parentheses pairing ({}[]()<>) issue

前端 未结 9 1552
醉酒成梦
醉酒成梦 2021-02-06 00:27

I want to be able to pair up all parentheses in a string, if they aren\'t paired then then they get their index number and False. It seems like it is repeating some values over

9条回答
  •  抹茶落季
    2021-02-06 00:45

    An understandable solution in Python 3:

    def check_balanced_string(str):
      stack = []
      dicc = {'(': ')', '[': ']', '{': '}'}
      for char in str:
        if char in dicc.keys():  # opening char
          stack.append(char)
        elif char in dicc.values():  # closing char
          if dicc[stack[-1]] == char:  # check if closing char corresponds to last opening char
            stack.pop()
          else:
            return False
      return not len(stack)  # returns True when len == 0
    
    eq = '{1+[3*5+(2+1)]}'
    print(check_balanced_string(eq))
    

提交回复
热议问题