Leetcode 1047. Remove All Adjacent Duplicates In String
Given a string s
, 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.
Input: s = "abbaca"
Output: "ca"
Input: s = "azxxzy"
Output: "ay"
1 <= s.length <= 10^5
s
consists of lowercase English letters.Before proceeding, let’s ensure we understand the problem thoroughly:
n
is the length of the string s
because each character is pushed onto and popped from the stack at most once.#include <iostream>
#include <stack>
#include <string>
std::string removeDuplicates(std::string s) {
std::stack<char> charStack;
for (char c : s) {
// If stack is not empty and top element is same as current char, pop the stack
if (!charStack.empty() && charStack.top() == c) {
charStack.pop();
} else {
charStack.push(c);
}
}
// Construct the result string from the stack
std::string result = "";
while (!charStack.empty()) {
result = charStack.top() + result;
charStack.pop();
}
return result;
}
// Example usage
int main() {
std::string s = "abbaca";
std::cout << "Result: " << removeDuplicates(s) << std::endl;
s = "azxxzy";
std::cout << "Result: " << removeDuplicates(s) << std::endl;
return 0;
}
This code correctly handles duplicate removals iteratively and outputs the resulting string when no more adjacent duplicates exist.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?