括号平衡的递归方法[python]

jon*_*nyc -4 python recursion function

任何人都知道如何编写一个使用递归平衡括号的函数?

我正在考虑计算每个外括号或内括号在字符串中弹出的次数,但是它会错过像“()())()(”或“)(”这样的情况。

我的老师有递归的例子来解决阶乘和计算斐波那契数列的数字,但她从来没有真正解决过其他类型的问题。

Rom*_*kar 6

def balanced(s, i=0, cnt=0):
    if i == len(s): return cnt == 0
    if cnt < 0: return False
    if s[i] == "(": return  balanced(s, i + 1, cnt + 1)
    elif s[i] == ")": return  balanced(s, i + 1, cnt - 1)
    return balanced(s, i + 1, cnt)

for s in ["()", "(()", "(())", "()()", ")("]:
    print "{}: {}".format(s, balanced(s))

(): True
((): False
(()): True
()(): True
)(: False
Run Code Online (Sandbox Code Playgroud)