Skip to content

2696. Minimum String Length After Removing Substrings 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int minLength(string s) {
    stack<char> stack;

    for (const char c : s)
      if (c == 'B' && match(stack, 'A'))
        stack.pop();
      else if (c == 'D' && match(stack, 'C'))
        stack.pop();
      else
        stack.push(c);

    return stack.size();
  }

 private:
  bool match(const stack<char>& stack, int c) {
    return !stack.empty() && stack.top() == c;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int minLength(String s) {
    Deque<Character> stack = new ArrayDeque<>();

    for (final char c : s.toCharArray())
      if (c == 'B' && match(stack, 'A'))
        stack.pop();
      else if (c == 'D' && match(stack, 'C'))
        stack.pop();
      else
        stack.push(c);

    return stack.size();
  }

  private boolean match(Deque<Character> stack, char c) {
    return !stack.isEmpty() && stack.peek() == c;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def minLength(self, s: str) -> int:
    stack = []

    def match(c: str) -> bool:
      return stack and stack[-1] == c

    for c in s:
      if c == 'B' and match('A'):
        stack.pop()
      elif c == 'D' and match('C'):
        stack.pop()
      else:
        stack.append(c)

    return len(stack)