问题描述
假设一个表达式有英文字母(小写)、运算符(+,—,*,/)和左右小(圆)括号构成,以“@”作为表达式的结束符。请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回“YES”;否则返回“NO”。表达式长度小于255,左圆括号少于20个。
输入格式
一行:表达式。
输出格式
一行:“YES” 或“NO”
输入样例
2*(x+y)/(1-x)@
输出样例
YES
代码
BRACKET = {')': '('}
BRACKET_L, BRACKET_R = BRACKET.values(), BRACKET.keys()
while 1:
s =str(input())
arr = []
a=0
for c in s:
if c in BRACKET_L:
# 左括号入栈
arr.append(c)
elif c in BRACKET_R:
# 右括号,要么栈顶元素出栈,要么匹配失败
if arr and arr[-1] == BRACKET[c]:
arr.pop()
else:
print('NO')
a=1
break
if arr == [] and a==0:
print('YES')
elif arr != []:
print('NO')