2516.cpp (586B)
1 class Solution { 2 public: 3 int takeCharacters(const string &s, int k) const { 4 const int n = size(s); 5 int count[3] = {0}; 6 7 for (const char c : s) 8 count[c - 'a']++; 9 if (count[0] < k || count[1] < k || count[2] < k) return -1; 10 11 int res = n; 12 for (int i = n - 1, j = n - 1; i >= 0; i--) { 13 count[s[i] - 'a']--; 14 15 while (count[0] < k || count[1] < k || count[2] < k) { 16 count[s[j--] - 'a']++; 17 } 18 19 res = min(res, i - j); 20 } 21 22 return res + n - 1; 23 } 24 };