题目
Given a string, write check(s) to check if the opening brackets ( match closing brackets ). Here we only
consider this type of parenthesis pairs. For example,
Matched pairs: (abc), (a(b(c))), expected return: True.
Unmatched pairs: (abc, (a))(, expected return: False.
方法一(删除相邻'(' 和’)' ):#实在有点傻
'(' 和’)' 的数目不一样多,not match
最后一个符号是'(',not match
重复删除相邻的'(' 和’)',如果一直删到空,则matach,如果剩下的最后一个符号还是‘(’,not match
def check(s):
list=[] #to collect all parenthese
odd=0
even=0
for ele in s:
if ele in ('(',')'):
if ele=='(':
odd+=1
else:
even+=1
list.append(ele)
if odd!=even:
return False
else:
return checkcore(list)
def checkcore(list):
if len(list)==0:
return True
if list[-1]=='(':
return False
for i in range(len(list)-1):
if list[i]=='(' and list[i+1]==')':
del list[i]
del list[i]
break
return checkcore(list)
def main3():
s1='(abc)'
s2='(a(b(c)))'
s3='(abc'
s4='(a)))()'
print(check(s1))
print(check(s2))
print(check(s3))
print(check(s4))
main3()
方法二(使用stack)
遇到打开的括号就往stack里面存一个,遇到关闭的括号且stack不为空就stack.pop(),
最后stack为空,则为True。
def check1(s):
stack=[]
for ele in s:
if ele=='(':
stack.append(ele)
elif ele==')':
if (len(stack)>0):
stack.pop()
else:
return False
if len(stack)==0:
return True
else:
return False
def main3():
s1='(abc)'
s2='(a(b(c)))'
s3='(abc'
s4='(a)))()'
print(check1(s1))
print(check1(s2))
print(check1(s3))
print(check1(s4))
main3()