Python program to check matching of simple parentheses

后端 未结 25 2346
谎友^
谎友^ 2020-12-01 17:02

I am a Python newbie and I came across this exercise of checking whether or not the simple brackets \"(\", \")\" in a given string are matched evenly.

I have seen ex

25条回答
  •  攒了一身酷
    2020-12-01 17:27

    here's another way to solve it by having a counter that tracks how many open parentheses that are difference at this very moment. this should take care all of the cases.

    def matched(str):
        diffCounter = 0
        length = len(str)
        for i in range(length):
            if str[i] == '(':
                diffCounter += 1
            elif str[i] == ')':
                diffCounter -= 1
        if diffCounter == 0:
            return True
        else:
            return False
    

提交回复
热议问题