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.
class Solution {
public:
int minLength(string s) {
stack<char> st;
for(char c:s){
if (c == 'B' && st.size() && st.top() == 'A') {
st.pop();
}
else if (c == 'D' && st.size() && st.top() == 'C') {
st.pop();
}else{
st.push(c);
}
}
return st.size();
}
};
class Solution:
def minLength(self, s: str) -> int:
return len(s) if "AB" not in s and "CD" not in s else self.minLength(s.replace("AB", "").replace("CD",""))
给定仅由大写字母组成的字符串s,通过一次操作移除子串AB或CD来减小长度。求最少可能的操作次数以达到最小长度。例如,输入ABFCACDB,最终长度为2。
398

被折叠的 条评论
为什么被折叠?



