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

前端 未结 9 1541
醉酒成梦
醉酒成梦 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:59

    Try this:

    def matched(s):
    stack=[]
    open,close="(",")" 
    for i in s:
        if i in open:
            stack.append(i)
        if i in close:
            if len(stack)==0:
                return(False)
            else:   
                stack.pop()
    if len(stack):
        return(False)
    else:
        return(True)
    
    0 讨论(0)
  • 2021-02-06 01:05

    You can adapt my code to a similar question:

    def Evaluate(str):
      stack = []
      pushChars, popChars = "<({[", ">)}]"
      for c in str :
        if c in pushChars :
          stack.append(c)
        elif c in popChars :
          if not len(stack) :
            return False
          else :
            stackTop = stack.pop()
            balancingBracket = pushChars[popChars.index(c)]
            if stackTop != balancingBracket :
              return False
        else :
          return False
      return not len(stack)
    
    0 讨论(0)
  • 2021-02-06 01:08

    First we will scan the string from left to right, and every time we see an opening parenthesis we push it to a stack, because we want the last opening parenthesis to be closed first. (Remember the FILO structure of a stack!) Then, when we see a closing parenthesis we check whether the last opened one is the corresponding closing match, by popping an element from the stack. If it’s a valid match, then we proceed forward, if not return false. Code: https://gist.github.com/i143code/51962bfb1bd5925f75007d4dcbcf7f55

    0 讨论(0)
提交回复
热议问题