def matched(s):
depth = 0
for x in s:
if x == '(':
depth += 1
elif x == ')' and depth != 0:
depth -= 1
return depth == 0
def matched2(s):
depth = 0
for x in s:
if x == '(':
depth += 1
elif x == ')': # and depth != 0:
depth -= 1 # this is not correct
return depth == 0
def main():
print(matched("zb%78")) # True
print(matched("(7)(a")) # False
print(matched("a)*(?")) # False
print(matched("((jkl)78(A)&l(8(dd(FJI:),):)?)")) # True
print()
print(matched2("zb%78")) # True
print(matched2("(7)(a")) # False
print(matched2("a)*(?")) # True
print(matched2("((jkl)78(A)&l(8(dd(FJI:),):)?)")) # True
if __name__ == '__main__':
main()
Comments
Leave a comment