Table of Contents
Description Minimum String Length After Removing Substrings
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
1 2 3 4 5 6 7 8 |
<strong>Input:</strong> s = "ABFCACDB" <strong>Output:</strong> 2 <strong>Explanation:</strong> 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
1 2 3 |
<strong>Input:</strong> s = "ACBBD" <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. |
Constraints
1 <= s.length <= 100
s
consists only of uppercase English letters.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution { public int minLength(String s) { if(s==null || s.isBlank()){ return 0; } ArrayDeque<Character> stack = new ArrayDeque<>(); for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(stack.isEmpty()){ stack.push(c); } else { if((c=='B' && stack.peek()=='A') || (c=='D' && stack.peek() == 'C')){ stack.pop(); } else { stack.push(c); } } } return stack.size(); } } |
Time Complexity
O(n), where n is the number of characters in a string
Space Complexity
O(n)