Skip to content

Commit e5afaa7

Browse files
committed
2. Longest Repeating Character Replacement
1 parent a657326 commit e5afaa7

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* 1. brute force -> time limited
5+
* 2. recursion -> failed to implement
6+
* 3. dynamic programming -> failed to implement
7+
* 4. dale solution https://www.algodale.com/problems/longest-repeating-character-replacement/
8+
* n: length of list1 + list2
9+
* time complexity: O(n^3)
10+
* space complexity: O(n)
11+
*/
12+
13+
/**
14+
* brute force
15+
* time complexity: O(n^3)
16+
* space complexity: O(n)
17+
*/
18+
// var characterReplacement = function (s, k) {
19+
// let answer = 0;
20+
// const set = new Set();
21+
// for (let i = 0; i < s.length; i++) set.add(s[i]);
22+
// for (let i = 0; i < s.length; i++) {
23+
// for (const now of set) {
24+
// let current = 0;
25+
// let count = k;
26+
27+
// for (let j = i; j < s.length; j++) {
28+
// if (now === s[j]) current++;
29+
// else if (count) {
30+
// current++;
31+
// count--;
32+
// }
33+
// break;
34+
// }
35+
// answer = Math.max(answer, current);
36+
// }
37+
// }
38+
39+
// return answer;
40+
// };
41+
42+
/**
43+
* time complexity: O(n)
44+
* space complexity: O(1)
45+
*/
46+
var characterReplacement = function (s, k) {
47+
let start = 0;
48+
let answer = 0;
49+
50+
const map = new Map();
51+
for (let i = 0; i < s.length; i++) map.set(s[i], 0);
52+
53+
for (let end = 0; end < s.length; end++) {
54+
map.set(s[end], map.get(s[end]) + 1);
55+
const maxLength = Math.max(...map.values());
56+
57+
while (end - start + 1 - maxLength > k) {
58+
map.set(s[start], map.get(s[start]) - 1);
59+
start++;
60+
}
61+
62+
answer = Math.max(end - start + 1, answer);
63+
}
64+
65+
return answer;
66+
};

0 commit comments

Comments
 (0)