-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-52.java
More file actions
62 lines (58 loc) · 1.76 KB
/
leet-code-q-52.java
File metadata and controls
62 lines (58 loc) · 1.76 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class Solution {
public int maxPartitionsAfterOperations(String s, int k) {
int n = s.length();
int[][] left = new int[n][3];
int[][] right = new int[n][3];
int num = 0;
int mask = 0;
int count = 0;
for (int i = 0; i < n - 1; i++) {
int binary = 1 << (s.charAt(i) - 'a');
if ((mask & binary) == 0) {
count++;
if (count <= k) {
mask |= binary;
} else {
num++;
mask = binary;
count = 1;
}
}
left[i + 1][0] = num;
left[i + 1][1] = mask;
left[i + 1][2] = count;
}
num = 0;
mask = 0;
count = 0;
for (int i = n - 1; i > 0; i--) {
int binary = 1 << (s.charAt(i) - 'a');
if ((mask & binary) == 0) {
count++;
if (count <= k) {
mask |= binary;
} else {
num++;
mask = binary;
count = 1;
}
}
right[i - 1][0] = num;
right[i - 1][1] = mask;
right[i - 1][2] = count;
}
int maxVal = 0;
for (int i = 0; i < n; i++) {
int seg = left[i][0] + right[i][0] + 2;
int totMask = left[i][1] | right[i][1];
int totCount = Integer.bitCount(totMask);
if (left[i][2] == k && right[i][2] == k && totCount < 26) {
seg++;
} else if (Math.min(totCount + 1, 26) <= k) {
seg--;
}
maxVal = Math.max(maxVal, seg);
}
return maxVal;
}
}