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