LeetCode 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.
Example 1:
Input: s = "abbaca"
Output: "ca"
method: 栈
题意:消掉相邻的重复字符,消掉之后又有重复相邻要继续消掉
直接用字符串当栈,如果当前元素和栈顶元素相同,就出栈
string removeDuplicates(string str) {
string ret;
for (auto s : str) {
if (ret.empty() || ret.back() != s) ret.push_back(s);
else ret.pop_back();
}
return ret;
}