def valid_parentheses(s: str) -> bool:
ind = 0
for i in s:
if i == '(':
ind += 1
elif i == ')':
ind -= 1
if ind < 0:
return False
if ind != 0:
return False
return True
assert valid_parentheses(" (") == False
assert valid_parentheses(")test") == False
assert valid_parentheses("") == True
assert valid_parentheses("hi())(") == False
assert valid_parentheses("hi(hi)()") == True
def valid_parentheses(s: str) -> bool:
bracket_dict = {")": "("}
stack = []
for i in s:
if i in bracket_dict:
if len(stack) > 0 and bracket_dict[i] == stack[-1]:
stack.pop()
else:
return False
elif i in bracket_dict.keys() or i in bracket_dict.values():
stack.append(i)
return not stack
def valid_parentheses(s: str) -> bool:
if s=='':return True
while '()' in s:
s=s.replace('()','')
if '(' in s and ')' in s and s.index('(')<s.index(')'):return True
else:return False
return False
新修改了一种
def valid_parentheses(s: str) -> bool:
if s == '': return True
list1,list2=[],[]
for i in s:
if i=='(':
num=s.index(i)
list1.append(num)
s=s.replace('(','x',1)
elif i==')':
num1=s.index(i)
list2.append(num1)
s=s.replace(')', 'x', 1)
if len(list1)==len(list2) and set(list(map(lambda x, y: x < y, list1, list2)))=={True}:
return True
else:
return False
def valid_parentheses(s: str) -> bool:
# your code here
pure_s = ""
if 0 <= len(s) <= 100:
for sub_str in s:
if sub_str in "()":
pure_s += sub_str
while "()" in pure_s:
pure_s = pure_s.replace("()", "")
return len(pure_s) == 0
return False
import re
def valid_parentheses(s: str):
i=0
left_index = [i.start() for i in re.finditer("\(",s)]
right_index=[i.start() for i in re.finditer("\)",s)]
if len(left_index)==len(right_index):
while i<len(left_index):
if left_index[i]<right_index[i]:
i+=1
continue
elif left_index[i]>right_index[i]:
return False
return True
else:
return False