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 is guaranteed that the answer is unique.
Example 1:
Input: s = "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" -> "bb" is removed -> You get "aaca" -> "aa" is removed -> You get "ca".
Example 2:
Input: s = "azxxzy"
Output: "ay"
s
contains only lowercase English letters.The approach is to use a stack to aid in removing the adjacent duplicates:
Here is the Java code for the solution:
import java.util.Stack;
public class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (!stack.isEmpty() && stack.peek() == ch) {
stack.pop();
} else {
stack.push(ch);
}
}
// Convert stack to string
StringBuilder result = new StringBuilder();
for (char ch : stack) {
result.append(ch);
}
return result.toString();
}
}
push
/pop
) is (O(1)).Using a stack allows us to efficiently handle the problem by keeping track of characters and easily removing adjacent duplicates as we traverse the string.
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?