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.
Example 1:
Input: s = "aabaaaacaabc", k = 2 Output: 8 Explanation: Take three characters from the left of s. You now have two 'a' characters, and one 'b' character. Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters. A total of 3 + 5 = 8 minutes is needed. It can be proven that 8 is the minimum number of minutes needed.
Example 2:
Input: s = "a", k = 1 Output: -1 Explanation: It is not possible to take one 'b' or 'c' so return -1.
Constraints:
1 <= s.length <= 105sconsists of only the letters'a','b', and'c'.0 <= k <= s.length
Related Topics:
Hash Table, String, Sliding Window
Similar Questions:
// OJ: https://leetcode.com/problems/take-k-of-each-character-from-left-and-right
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
int takeCharacters(string s, int k) {
int N = s.size(), L = 3 * k, R = N;
auto valid = [&](int len) {
int cnt[3] = {};
for (int i = 0; i < len; ++i) {
cnt[s[i] - 'a']++;
}
for (int i = 0; i <= len; ++i) {
if (i > 0) {
cnt[s[N - i] - 'a']++;
cnt[s[len - i] - 'a']--;
}
int j = 0;
while (j < 3 && cnt[j] >= k) ++j;
if (j == 3) return true;
}
return false;
};
while (L <= R) {
int M = (L + R) / 2;
if (valid(M)) R = M - 1;
else L = M + 1;
}
return L > N ? -1 : L;
}
};// OJ: https://leetcode.com/problems/take-k-of-each-character-from-left-and-right
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int takeCharacters(string s, int k) {
if (k == 0) return 0;
int N = s.size(), cnt[3] = {}, i = 0;
auto valid = [&]() {
int j = 0;
while (j < 3 && cnt[j] >= k) ++j;
return j == 3;
};
for (; i < N; ++i) {
cnt[s[i] - 'a']++;
if (valid()) break;
}
if (i == N) return -1;
int ans = i + 1, j = N - 1;
for (; i >= 0; --j) {
cnt[s[j] - 'a']++;
while (valid()) {
ans = min(ans, N - j + i + 1);
if (i >= 0) cnt[s[i--] - 'a']--;
else break;
}
}
return ans;
}
};// OJ: https://leetcode.com/problems/take-k-of-each-character-from-left-and-right
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int takeCharacters(string s, int k) {
if (k == 0) return 0;
int cnt[3] = {}, limits[3] = {}, N = s.size(), i = 0, j = 0;
for (char c : s) limits[c - 'a']++;
for (int i = 0; i < 3; ++i) {
limits[i] -= k;
if (limits[i] < 0) return -1;
}
auto valid = [&]() {
int j = 0;
while (j < 3 && cnt[j] <= limits[j]) ++j;
return j == 3;
};
for (; j < N; ++j) {
cnt[s[j] - 'a']++;
if (!valid()) {
cnt[s[i] - 'a']--;
++i;
}
}
return N - j + i;
}
};