一、题目
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:文章来源:https://www.toymoban.com/news/detail-823726.html
1 <= s.length <= 100
s consists only of uppercase English letters.文章来源地址https://www.toymoban.com/news/detail-823726.html
二、题解
class Solution {
public:
bool existed(string s){
if(s.size() < 2) return false;
int n = s.size();
for(int i = 0;i < n - 1;i++){
if(s[i] == 'A' && s[i + 1] == 'B') return true;
if(s[i] == 'C' && s[i + 1] == 'D') return true;
}
return false;
}
int minLength(string s) {
while(existed(s)){
for(int i = 0;i < s.size() - 1;i++){
if(s[i] == 'A' && s[i + 1] == 'B'){
s.erase(s.begin() + i);
s.erase(s.begin() + i);
i--;
}
else if(s[i] == 'C' && s[i + 1] == 'D'){
s.erase(s.begin() + i);
s.erase(s.begin() + i);
i--;
}
if(s.size() == 0) return 0;
}
}
return s.size();
}
};
到了这里,关于LeetCode2696. Minimum String Length After Removing Substrings的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!