Similar Problem:
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.
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".
- Use stack to maintain unique characters to the respect of the current left
- only add to stack if there is no duplicate in the stack or the stack is empty
- if the top of the stack is a duplicate remove it and not add the current
- construct the final answer by the reverse order of the stack
Time: O(n)
Space: O(n)
public String removeDuplicates(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (stack.isEmpty() || stack.peekLast() != c)
stack.addLast(c);
else
stack.removeLast();
}
StringBuilder ans = new StringBuilder();
while (!stack.isEmpty())
ans.append(stack.removeFirst());
return ans.toString();
}