Skip to content

Commit 8738cee

Browse files
authored
Create Take K of Each Character From Left and Right.java
1 parent 5eaf013 commit 8738cee

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int takeCharacters(String s, int k) {
3+
int[] counter = new int[3];
4+
int n = s.length();
5+
for (char c : s.toCharArray()) {
6+
counter[c - 'a']++;
7+
}
8+
for (int i = 0; i < 3; i++) {
9+
if (counter[i] < k) {
10+
return -1;
11+
}
12+
}
13+
int[] window = new int[3];
14+
int left = 0;
15+
int maxWindow = 0;
16+
for (int right = 0; right < n; right++) {
17+
window[s.charAt(right) - 'a']++;
18+
while (left <= right &&
19+
(counter[0] - window[0] < k || counter[1] - window[1] < k || counter[2] - window[2] < k)) {
20+
window[s.charAt(left) - 'a']--;
21+
left++;
22+
}
23+
maxWindow = Math.max(maxWindow, right - left + 1);
24+
}
25+
return n - maxWindow;
26+
}
27+
}

0 commit comments

Comments
 (0)