forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0424-longest-repeating-character-replacement.js
78 lines (61 loc) · 1.77 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* 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 res = 0;
let count = new Map();
let l = 0;
for (let r = 0; r < s.length; r++) {
let len = r - l + 1
count.set(s[r], 1 + (count.get(s[r]) || 0))
if ((len - Math.max(...count.values())) > k) {
count.set(s[l], count.get(s[l]) - 1)
l++;
}
len = r - l + 1;
res = Math.max(res, len)
}
return res;
};
/**
* 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);