1047. Remove All Adjacent Duplicates In String
Question
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" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Example 2:
Input: s = "azxxzy" Output: "ay"
Constraints:
1 <= s.length <= 10 5sconsists of lowercase English letters.
Solutions
Approach 1 : use stack
Time Complexity: O(N)
Space Complexity: O(N)
string removeDuplicates(string s) {
// use stack approach:
// put each elements into the stack and peak the top every time.
// if top value equals to current val, then skip push current value and pop
// at the end , the result is stored in the stack but a reversed order. need to pop them back and reorder.
// the top from the stack. edge cases:
// 1. when s.size is 0 ->
// 2. when s.size is 1 ->
// 3. when all chars are distince ->
// 4. when all chars are identical ->
// Time Complexity: O(N)
// Space Complexity: O(N) -> worse case need N items stack.
// examples: "abbaca" -> "ca" (correct)
// examples: "azxxzy" -> "ay" (correct)
// examples: "aaaaz" -> "z" (correct)
// examples: "" -> "" (correct)
// examples: "abcd" -> "abcd" (correct)
stack<char> st;
int n = static_cast<int>(s.size());
for (int i = 0; i < n; ++i) {
if (st.empty()) {
st.push(s[i]);
continue;
}
char topChar = st.top();
if (topChar == s[i]) {
st.pop();
} else {
st.push(s[i]);
}
}
string result;
while (!st.empty()) {
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}