Skip to content

Commit 3de0ee0

Browse files
committed
Feat: 424. Longest Repeating Character Replacement
1 parent e765811 commit 3de0ee0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* https://leetcode.com/problems/longest-repeating-character-replacement
3+
* T.C. O(n)
4+
* S.C. O(1)
5+
*/
6+
function characterReplacement(s: string, k: number): number {
7+
const charCount = new Array(26).fill(0);
8+
let maxCount = 0;
9+
let start = 0;
10+
let maxLen = 0;
11+
12+
const A = 'A'.charCodeAt(0);
13+
for (let end = 0; end < s.length; end++) {
14+
const endCharIdx = s.charCodeAt(end) - A;
15+
maxCount = Math.max(maxCount, ++charCount[endCharIdx]);
16+
17+
if (end - start + 1 - maxCount > k) {
18+
charCount[s.charCodeAt(start) - A]--;
19+
start++;
20+
}
21+
22+
maxLen = Math.max(maxLen, end - start + 1);
23+
}
24+
return maxLen;
25+
}

0 commit comments

Comments
 (0)