forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0424-longest-repeating-character-replacement.js
51 lines (38 loc) · 1.15 KB
/
0424-longest-repeating-character-replacement.js
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
/**
* https://leetcode.com/problems/longest-repeating-character-replacement/
* Time O(((N + 26) * N) * (M - N)) | Space O(1)
* @param {string} s
* @param {number} k
* @return {number}
*/
var characterReplacement = function (s, k) {
let [left, right, longest, max] = new Array(4).fill(0);
const frequencyMap = new Array(26).fill(0);
while (right < s.length) {
const count = addRightFrequency(s, right, frequencyMap);
longest = Math.max(longest, count);
let window = right - left + 1;
const canSlide = k < window - longest;
if (canSlide) {
subtractLeftFrequency(s, left, frequencyMap);
left++;
}
window = right - left + 1;
max = Math.max(max, window);
right++;
}
return max;
};
const addRightFrequency = (s, right, map) => {
const char = s[right];
const index = getCode(char);
map[index]++;
return map[index];
};
const subtractLeftFrequency = (s, left, map) => {
const char = s[left];
const index = getCode(char);
map[index]--;
return map[index];
};
const getCode = (char) => char.charCodeAt(0) - 'A'.charCodeAt(0);