题解 | 点击消除
点击消除
https://www.nowcoder.com/practice/8d3643ec29654cf8908b5cf3a0479fd5
- 通过使用栈(stack)管理每一个遍历的字符:
- 如果:栈顶元素与当前字符相同,则弹出栈(移除字符);
- 否则:将当前字符压入栈中;
- 遍历完成后,检查栈空:
- 如果:栈空,直接输出 “0” 结束;
- 否则:直接将栈的内容按序输出即可(因为前面已经是逆向入栈,可以保证顺序出栈)。
- 复杂度分析:
- 时间O(n):遍历
- 空间O(n):输入串长度,栈最坏保存所有字符
#include<iostream> #include<stack> using namespace std; int main() { string s; while (cin >> s) { stack<char> stack; // 逆向遍历整个输入字符串:这样在输出的时候可以直接输出而无需重组字符串; for (auto it = s.rbegin(); it != s.rend(); it++) { if (!stack.empty() && *it == stack.top()) stack.pop(); else stack.push(*it); } // 处理最后是空的情况,需要输出 “0” if (stack.empty()) { cout << "0" << endl; continue; } // 直接出栈输出结果 while (!stack.empty()) { cout << stack.top(); stack.pop(); } cout << endl; } return 0; }