Two Pointers Sliding Window
一开始理解错题意了,以为window里面最多只有两种不同的char
后来发现是window里可以有最多k个和最大char不一样的char
每次需要维持count最大的char,一开始是以为是PriorityQueue
问题在于pq的remove time是O(m)
还不如直接扫一遍 m = 26约等于constant
67.66 %
class Solution {
public int characterReplacement(String s, int k) {
int[] count = new int[26];
int left = -1;
int right = 0;
int max = 0;
// (left, right]
int curr;
for (right = 0; right < s.length(); right++) {
curr = s.charAt(right) - 'A';
count[curr]++;
while (check(count) > k) {
left++;
curr = s.charAt(left) - 'A';
count[curr]--;
}
max = Math.max(max, right - left);
}
return max;
}
private int check(int[] count) {
int sum = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < count.length; i++) {
sum += count[i];
max = Math.max(max, count[i]);
}
return sum - max;
}
}
No comments:
Post a Comment