Remove All Adjacent Duplicates In String

easy stack string

Problem

You are given a string s of lowercase English letters. A duplicate removal deletes two adjacent equal characters. Repeatedly perform duplicate removals until no more can be made, and return the final string. The answer is guaranteed to be unique.

Inputs = "abbaca"
Output"ca"
Remove "bb" to get "aaca", then remove "aa" to get "ca". No adjacent duplicates remain.

def remove_duplicates(s):
    stack = []
    for ch in s:
        if stack and stack[-1] == ch:
            stack.pop()
        else:
            stack.append(ch)
    return "".join(stack)
function removeDuplicates(s) {
  const stack = [];
  for (const ch of s) {
    if (stack.length && stack[stack.length - 1] === ch) {
      stack.pop();
    } else {
      stack.push(ch);
    }
  }
  return stack.join("");
}
class Solution {
    public String removeDuplicates(String s) {
        StringBuilder stack = new StringBuilder();
        for (char ch : s.toCharArray()) {
            int n = stack.length();
            if (n > 0 && stack.charAt(n - 1) == ch) {
                stack.deleteCharAt(n - 1);
            } else {
                stack.append(ch);
            }
        }
        return stack.toString();
    }
}
string removeDuplicates(string s) {
    string stack;
    for (char ch : s) {
        if (!stack.empty() && stack.back() == ch) {
            stack.pop_back();
        } else {
            stack.push_back(ch);
        }
    }
    return stack;
}
Time: O(n) Space: O(n)