mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 18:24:23 +08:00
833 B
833 B
题目地址
https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/
思路
这道题目就像是我们玩过的游戏对对碰, 可以把字符串放到与一个栈中,然后如果相同的话 栈就弹出,这样最后栈里剩下的元素都是相邻不相同的元素了
C++代码
class Solution {
public:
string removeDuplicates(string S) {
stack<char> st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
} else {
st.pop();
}
}
string result = "";
while(!st.empty()) {
result += st.top();
st.pop();
}
reverse(result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};