吐泡泡
吐泡泡
https://ac.nowcoder.com/acm/problem/15029
核心
没什么核心,其实就是括号匹配的板子题,基本上一模一样;
注意的地方,例如以下代码
if(!s.empty()&&s.top()=='O')
如果把!s.empty()放到&&后面那么编译的时候会出问题,所以栈的非空判断要放在前面;
处理完之后呢,栈中保存的结果是正确的,但是栈的特点是后进先出,所以需要一个字符数组来存栈的内容,然后在逆序输出;
int num=0;
while(!s.empty()){
c[num]=s.top();
s.pop();
num++;
}
for(int i=num-1;i>=0;i--)cout<<c[i];
cout<<endl;
}就这些注意事项吧;
贴上ac代码
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
using namespace std;
char c[1000];
stack<char>s;
int main(){
std::ios::sync_with_stdio(false);
string x;
while(cin>>x){
for(int i=0;i<x.length();i++)
{
if(s.empty()){
s.push(x[i]);
continue;
}
if(x[i]!=s.top()){
s.push(x[i]);
continue;
}else{
if(x[i]=='O')s.pop();
else {
s.pop();
if(!s.empty()&&s.top()=='O')s.pop();
else s.push('O');
}
}
}
int num=0;
while(!s.empty()){
c[num]=s.top();
s.pop();
num++;
}
for(int i=num-1;i>=0;i--)cout<<c[i];
cout<<endl;
}
return 0;
}
查看7道真题和解析