Minimum String Length After Removing Substrings Problem
Description
LeetCode Problem 2696.
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.
Example 1:
Input: s = "ABFCACDB"
Output: 2
Explanation: We can do the following operations:
- Remove the substring "ABFCACDB", so s = "FCACDB".
- Remove the substring "FCACDB", so s = "FCAB".
- Remove the substring "FCAB", so s = "FC".
So the resulting length of the string is 2.
It can be shown that it is the minimum length that we can obtain.
Example 2:
Input: s = "ACBBD"
Output: 5
Explanation: We cannot do any operations on the string so the length remains the same.
Constraints:
1 <= s.length <= 100sconsists only of uppercase English letters.
Solution
Approach: Stack
Scan the string and keep a stack of the characters that survive. When the current character c completes a pair with the top of the stack (A then B, or C then D), pop the top. Otherwise push c. Whatever is left in the stack is the shortest string.
Starting with a dummy empty character in the stack means we never have to check whether it is empty. The answer is then the stack size minus one.
Complexity: O(n) time and O(n) space.
class Solution:
def minLength(self, s: str) -> int:
stk = [""]
for c in s:
if (c == "B" and stk[-1] == "A") or (c == "D" and stk[-1] == "C"):
stk.pop()
else:
stk.append(c)
return len(stk) - 1