题解 | 吐泡泡
吐泡泡
https://www.nowcoder.com/practice/f86fa2221c094b3d8d1fc79bae450d96
#include <algorithm>
#include <cctype>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int T;
cin >> T;
for (int i = 0; i < T; i++) // 多组数据
{
// 输入数据
string str;
cin >> str;
// 初始化栈
stack<char> st;
// 循环读入每一项然后根据规则合并
for (int j = 0; str[j] != '\0'; j++)
{
// 如果是空栈,直接push进去
if (empty(st) == true)
{
st.push(str[j]);
}
else // 不是空栈,准备处理
{
// 循环处理
char ch = str[j];
if (ch != st.top()) // 如果和栈顶不相同,不用管直接push
{
st.push(ch);
}
else // 有相同的,开始进行操作
{
char ch = str[j]; // 最终需要push进栈的字符
int flag = 0;
while (ch == st.top()) // 相同时重复执行
{
if (ch == 'o') // 合并
{
st.pop();
ch = 'O';
}
else // 爆炸,直接break,不需要push
{
st.pop();
flag = 1;
break;
}
// 检查是否空栈
if (empty(st) == true)
{
break;
}
}
if (!flag) // 没爆炸
{
st.push(ch);
}
}
}
}
// 输出
stack<char> ans;
while (!st.empty())
{
ans.push(st.top());
st.pop();
}
while (!ans.empty())
{
cout << ans.top();
ans.pop();
}
cout << '\n';
}
}

查看6道真题和解析