题目链接: 点我跳转
题目大意: 给定一个字符串,判断其中的左右括号是否配对
题目分析: 洛谷归类在线性结构里面,应该是用栈,那么我们遇到左括号,就在栈里面放一个1,遇到右括号就取出一个1来,如果结束的时候还有1在里面,就是配对成功,没空就是失败。如果在读取的过程中栈空了又遇到了右括号,那也说明配对失败。但是我们好像只用到了栈的大小,所以用一个数字来表示栈的大小就OK了。
用栈写的代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<stack>
using namespace std;
int main(){
char x;
int t;
stack<int> stk;
while(1){
cin>>x;
if(x == '@'){
if(stk.empty())printf("YES");
else printf("NO");
break;
}
t = (x == '(')-(x == ')');//左括号为1,右括号为-1,其他字符为0
if(t == 1)stk.push(1);//随便放进去一个数字好了反正不重要
else if(t == -1){
if(stk.empty()){
printf("NO");
break;
}
stk.pop();
}
}
return 0;
}
这是不用栈的版本
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int main(){
char x;
int t,stk(0);
while(1){
cin>>x;
if(x == '@'){
if(!stk)printf("YES");
else printf("NO");
break;
}
t = (x == '(')-(x == ')');
if(t == 1)stk++;
else if(t == -1){
if(!stk){
printf("NO");
break;
}
stk--;
}
}
return 0;
}