Description
在实际编程中,我们经常会嵌套使用括号,如“{}”、“[]” 、 “()”,如果括号太多,可能会出现括号不匹配的情况,比如“(as))”、“{(bcd})”等。现编写一个程序,判断输入的一段语句中的括号是否匹配。
def func(S):
mylist=[]
index = -1
#由于continue,index不能放在循环体最后,进而index<=len(S)-2
while index < len(S)-1:
index += 1
sym = S[index] #存储字符
if sym == '(' or sym == '[' or sym == '{':
mylist.append(sym) #有左括号时压栈
#注意:分类讨论
else:
if sym == ')':
if len(mylist)>0 and mylist.pop()=='(':
continue
else:
return False
if sym == ']':
if len(mylist)>0 and mylist.pop()=='[':
continue
else:
return False
if sym == '}':
if len(mylist)>0 and mylist.pop()=='{':
continue
else:
return False
if len(mylist) == 0:
return True
else:
return False
S = input()
print(func(S))
一个要注意的地方,右括号一定要分别讨论。
括号匹配,是在左括号、右括号个数相等的基础上的。比如:
Print(abc[0{+’This is a ]}’) 左右括号个数相同,但不匹配,所以为False。