Repeatedly remove occurrences of fixed substrings until none remain, and return the final string length.
Remove All Occurrences of a Substring
gfgProblem
You are given a string s made up of uppercase English letters. In one operation, you may remove any occurrence of either substring "AB" or "CD" from the string.
Keep performing this operation as long as possible. Return the minimum possible length of the string after all valid removals have been made.
The order of characters that remain must stay the same relative to each other; only whole matching substrings can be deleted.
Goal
Find the length of the shortest string obtainable after repeatedly deleting "AB" and "CD" wherever they appear.
Input Format
- A single string
sconsisting of uppercase English letters. - You may assume the only removable substrings are
"AB"and"CD".
Output Format
- Return a single integer: the minimum final length of the string after all possible removals.
Constraints
1 <= s.length <= 100scontains only uppercase English letters.- Only adjacent pairs
"AB"and"CD"may be removed.
Example 1
Input
s = "ABFCACDB"
Output
2
Explanation
One valid sequence is: remove AB -> FCACDB, remove CD -> FCAB, remove AB -> FC. The final length is 2.
Example 2
Input
s = "ACBBD"
Output
5
Explanation
No substring AB or CD appears, so nothing can be removed.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.