Minimum String Length After Removing Substrings

medium string stack simulation

Problem

You are given a string s of only the characters A, B, C and D. In one operation you may delete any occurrence of the substring "AB" or the substring "CD". After deleting, the string joins back together and may form new "AB" or "CD" pairs, which you can keep deleting. Return the minimum possible length of the string after any number of operations.

Inputs = "ABFCACDB"
Output2
"ABFCACDB" → remove AB → "FCACDB" → remove CD → "FCAB" → remove AB → "FC". Length 2.

def min_length(s):
    stack = []
    for c in s:
        if stack and ((stack[-1] == 'A' and c == 'B') or
                      (stack[-1] == 'C' and c == 'D')):
            stack.pop()
        else:
            stack.append(c)
    return len(stack)
function minLength(s) {
  const stack = [];
  for (const c of s) {
    const top = stack[stack.length - 1];
    if (stack.length && ((top === 'A' && c === 'B') ||
                         (top === 'C' && c === 'D'))) {
      stack.pop();
    } else {
      stack.push(c);
    }
  }
  return stack.length;
}
class Solution {
    public int minLength(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (!stack.isEmpty() && ((stack.peek() == 'A' && c == 'B') ||
                                    (stack.peek() == 'C' && c == 'D'))) {
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        return stack.size();
    }
}
int minLength(string s) {
    string stack = "";
    for (char c : s) {
        if (!stack.empty() && ((stack.back() == 'A' && c == 'B') ||
                              (stack.back() == 'C' && c == 'D'))) {
            stack.pop_back();
        } else {
            stack.push_back(c);
        }
    }
    return stack.size();
}
Time: O(n) Space: O(n)