题目描述
假设一个表达式有英文字母(小写)、运算符(+,-,*,/)和左右小(圆)括号( )构成,以@作为表达式的结束符。请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回YES;否则返回NO。
输入格式
一行,一个表达式。
输出格式
一行,YES或NO,注意大小写。
样例1
输入数据 1
2*(x+y)/(1-x)@
Copy
输出数据 1
YES
Copy
样例2
输入数据 2
(25+x)*(a*(a+b+b)@
Copy
输出数据 2
NO
Copy
数据范围
表达式长度小于255,左圆括号少于20个。
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
using namespace std;
int main(){
stack <char> s;
int i;
char c;
while(scanf("%c", &c)){
if(c=='@'){
break;
}
if(c=='('||c=='['||c=='{'){
s.push(c);
}
if(c == ')'){
if(s.empty()){
printf("NO");
return 0;
}
if(s.top() == '('){
s.pop();
}
else{
printf("NO");
return 0;
}
}
if(c == ']'){
if(s.empty()){
printf("NO");
return 0;
}
if(s.top() == '['){
s.pop();
}
else{
printf("NO");
return 0;
}
}
if(c=='}'){
if(s.empty()){
printf("NO");
return 0;
}
if(s.top()=='{'){
s.pop();
}
else{
printf("NO");
return 0;
}
}
}
if(s.empty()){
printf("YES");
}
else{
printf("NO");
}
return 0;
}