[LeetCode] Minimum String Length After Removing Substrings

2696. 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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int minLength(string s) {
string res = "";
for(auto ch : s) {
if(ch == 'B' and res.size() and res.back() == 'A') res.pop_back();
else if(ch == 'D' and res.size() and res.back() == 'C') res.pop_back();
else res.push_back(ch);
}
return res.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/21/PS/LeetCode/minimum-string-length-after-removing-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.