Skip to content

Commit e540bc1

Browse files
authored
Create take-k-of-each-character-from-left-and-right.cpp
1 parent e891717 commit e540bc1

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// sliding window, two pointers
5+
class Solution {
6+
public:
7+
int takeCharacters(string s, int k) {
8+
vector<int> cnt(3);
9+
for (const auto& c : s) {
10+
++cnt[c - 'a'];
11+
}
12+
if (*min_element(cbegin(cnt), cend(cnt)) < k) {
13+
return -1;
14+
}
15+
int result = 0;
16+
for (int right = 0, left = 0; right < size(s); ++right) {
17+
--cnt[s[right] - 'a'];
18+
while (cnt[s[right] - 'a'] < k) {
19+
++cnt[s[left++] - 'a'];
20+
}
21+
result = max(result, right - left + 1);
22+
}
23+
return size(s) - result;
24+
}
25+
};

0 commit comments

Comments
 (0)