一.题目解析

这就很象我们玩过的消消乐游戏,我们来模拟一下:

这就很象我们的栈数据结构

数据结构栈就不再过多描述
代码编写:stack()容器
cpp
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (char ch : s) { // 遍历每个字符
// 如果栈不为空 且 栈顶 == 当前字符 → 重复,弹出
if (!st.empty() && st.top() == ch) {
st.pop();
} else {
st.push(ch); // 不重复就入栈
}
}
// 把栈里的字符拼成结果
string ret;
while (!st.empty()) {
ret += st.top();
st.pop();
}
reverse(ret.begin(), ret.end()); // 反转得到正确顺序
return ret;
}
};
我们其实可以用数组模拟栈结构

代码编写:string模拟栈结构
cpp
#include<bits/stdc++.h>
class Solution {
public:
string removeDuplicates(string s) {
string ret;
for(auto ch:s)
{
if(!ret.empty()&&ch==ret.back())ret.pop_back();
else ret+=ch;
}
return ret;
}
};