判断括号是否匹配–python
作者:互联网
例子:
valid_parentheses('i(hi)()') == True
valid_parentheses('hi())(') == False
valid_parentheses('') == True
valid_parentheses('())(())') == False
实现:
方法一:
def valid_parentheses(string): cnt = 0 for char in string: if char == '(': cnt += 1 if char == ')': cnt -= 1 if cnt < 0: return False return True if cnt == 0 else False
方法二:
def valid_parentheses(string): bb = ''.join(re.findall('[()]', string)) cc = bb.replace("()", "") return False if len(cc) else True
标签:cnt,parentheses,匹配,string,python,括号,valid,False,True 来源: https://www.cnblogs.com/lxz123/p/16317653.html