[LeetCode] Remove All Adjacent Duplicates In String

1047. Remove All Adjacent Duplicates In String

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string removeDuplicates(string s) {
vector<char> st;
queue<char> q;
for(auto ch : s) q.push(ch);
while(!q.empty()) {
while(!st.empty() and st.back() == q.front()) {
st.pop_back();
q.pop();
}
if(!q.empty()) {
st.push_back(q.front());
q.pop();
}
}

stringstream ss;
for(auto ch : st) ss<<ch;
return st.empty() ? "" : ss.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/remove-all-adjacent-duplicates-in-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.