[LeetCode] Take K of Each Character From Left and Right

2516. Take K of Each Character From Left and Right

You are given a string s consisting of the characters ‘a’, ‘b’, and ‘c’ and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s.

Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
int takeCharacters(string s, int k) {
if(k == 0) return 0;
int res = INT_MAX;
int a = 0, b = 0, c = 0, p = 0;
while(p < s.length()) {
if(s[p] == 'a') a += 1;
if(s[p] == 'b') b += 1;
if(s[p] == 'c') c += 1;
if(a >= k and b >= k and c >= k) break;
p += 1;
}
if(a < k or b < k or c < k) return -1;
res = min(res, p + 1);
int r = s.length() - 1;
while(p >= 0) {
if(s[p] == 'a') a -= 1;
if(s[p] == 'b') b -= 1;
if(s[p] == 'c') c -= 1;
while(a < k or b < k or c < k) {
if(s[r] == 'a') a += 1;
if(s[r] == 'b') b += 1;
if(s[r] == 'c') c += 1;
r -= 1;
}
if(a >= k and b >= k and c >= k) {
res = min(res,p + (int)s.length() - r - 1);
}
p -= 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/25/PS/LeetCode/take-k-of-each-character-from-left-and-right/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.