Skip to content

Commit 3daaeec

Browse files
committed
Longest Repeating Character Replacement
1 parent ddabf0b commit 3daaeec

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// TC: O(26 * n) => O(n)
2+
// iterates 26 times at the first for-loop, while loop O(n)
3+
// SC: O(1)
4+
class Solution {
5+
public int characterReplacement(String s, int k) {
6+
int ans = 0;
7+
int n = s.length();
8+
for (char c = 'A'; c <= 'Z'; c++) {
9+
int i = 0, j = 0, replaced = 0;
10+
while (j < n) {
11+
if (s.charAt(j) == c) {
12+
j += 1;
13+
} else if (replaced < k) {
14+
j += 1;
15+
replaced++;
16+
} else if (s.charAt(i) == c) {
17+
i += 1;
18+
} else {
19+
i += 1;
20+
replaced -= 1;
21+
}
22+
ans = Math.max(ans, j - i);
23+
}
24+
}
25+
return ans;
26+
}
27+
}

0 commit comments

Comments
 (0)