class Solution:
def isValid(self, s: str) -> bool:
dict={')':'(',']':'[','}':'{'}
stack=[]
for i in s:
if i in dict:
top=stack.pop() if stack else '%'
if dict[i]!=top:
return False
else:
stack.append(i)
return not bool(stack)
题解里的答案简直是太好用了,pop()在这里非常适合,可获取栈顶的值,并且同时将其从栈中退出,一举两得
class Solution:
def isValid(self, s: str) -> bool:
if s=="":return True
list_open={"(":1,"[":2,"{":3}
list_close={")":1,"]":2,"}":3}
num_open=0
num_close=0
result=True
for i in s:
if i in list_open:num_open+=1
if i in list_close:num_close+=1
if num_open==num_close:
half_window=0
for idx,j in enumerate(s):
if j in list_open:
half_window+=1
else:
left=idx-half_window
right=idx+half_window-1
while left<right:
for k in range(half_window):
if s[left]==s[right]:
left-=1
right+=1
if right-left==1:half_window=0
else: result=False
return result
else:
return False
反观自己一开始写的,废了半天的劲儿,写出来一个超时的/。。。。