[LeetCode] Minimum Length of String After Operations

3223. Minimum Length of String After Operations

You are given a string s.

You can perform the following process on s any number of times:

  • Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i].
  • Delete the closest character to the left of index i that is equal to s[i].
  • Delete the closest character to the right of index i that is equal to s[i].

Return the minimum length of the final string s that you can achieve.

1
2
3
4
5
6
7
8
9
10
11
12
13

class Solution {
public:
int minimumLength(string s) {
unordered_map<char,int> freq;
for(auto& ch : s) freq[ch]++;
int res = 0;
for(auto& [_,cnt] : freq) {
res += (cnt % 2 ? 1 : 2);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/21/PS/LeetCode/minimum-length-of-string-after-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.