Python program to check matching of simple parentheses

后端 未结 25 2412
谎友^
谎友^ 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:15

    if the parenthesis sequence is not an issue (strings like )( ) this code is faster :

    def matched_parenthesis(s):
        return s.count('(') == s.count(')')
    

    Tested with 15KB string, it is ~20μs v.s. 1ms iterating over the whole string.

    And for me the order is not an issue as the underlying protocol guaranties that the string is well-formed.

提交回复
热议问题