March 07, 2022

1047. Remove All Adjacent Duplicates In String

1047. Remove All Adjacent Duplicates In String

class Solution {
    public String removeDuplicates(String s) {
        Deque<Character> stack = new LinkedList<>();
        for (char c : s.toCharArray()) {
            if (!stack.isEmpty() && stack.peekFirst() == c) {
                stack.pollFirst();
            } else {
                stack.offerFirst(c);
            }
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pollFirst());
        }
        return sb.reverse().toString();
    }
}
comments powered by Disqus