看了题解中间都是用栈写的,我来补充一个用队列写的。
前面都是一样的,判断,压入弹出。但是到后面就是用队列的好处,直接从头部出去,不需要额外的空间。
另外,for (char &c : str)是C11的新语法,意为对str中所有元素遍历一遍,将每个元素依次赋值(或引用)给c进行循环
代码如下
#include<iostream>
#include<deque>
#include<string>
using namespace std;
deque<char> st;
string str;
int main() {
while (cin >> str) {
for (char &c : str) {
if (st.empty()||st.back()!=c) st.push_back(c);
else{
if (c == 'o') {
st.pop_back();
if (!st.empty() && st.back() == 'O') st.pop_back();
else st.push_back('O');
}
else st.pop_back();
}
}
while (!st.empty()) { cout << st.front(); st.pop_front(); }
}
}
京公网安备 11010502036488号