从Leetcode 每日一题练习继续讨论:
3223. 操作后字符串的最短长度
3223. Minimum Length of String After Operations
题解
本题考虑题中所述的操作,可以发现无需知道字符所在的具体位置,当一个字符在字符串中的个数大于等于3个时,处在中间位置的字符一定满足题目所述的条件并可以将两侧的字符删除,并可如此反复直到字符的个数小于3个,由此发现只需统计字符的个数,当字符个数为奇数时,则可以将中间位置的字符两侧不断删除直到只剩下正中间的字符,而为偶数时则不断删除后最终会剩余两个字符。再将所有字符的剩余个数加和即得结果。
代码
class Solution {
public:
int minimumLength(string s) {
vector<int> chars(26,0);
for(const auto& ch : s){
chars[ch-'a']++;
}
int result = 0;
for(const int& count : chars){
if(count > 0){
if(count % 2 == 0){
result += 2;
}else{
result += 1;
}
}
}
return result;
}
};