Skip to main content
Back to problems
#2696
Easy Algorithms

Minimum string length after removing substrings

String Stack Simulation
77.1% acceptance
Feb 25, 2026
1009
29
You are given a string s consisting only of uppercase English letters. You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings "AB" or "CD" from s. Return the minimum possible length of the resulting string that you can obtain. Note that the string concatenates after removing the substring and could produce new "AB" or "CD" substrings.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_length(s: String) -> i32 {
    let mut stack: Vec<u8> = Vec::new();
    for b in s.bytes() {
      if let Some(&top) = stack.last() {
        if (top == b'A' && b == b'B') || (top == b'C' && b == b'D') {
          stack.pop();
          continue;
        }
      }
      stack.push(b);
    }
    stack.len() as i32
  }
}