Skip to content

Commit

Permalink
Longest Repeating Character Replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyKim9401 committed Oct 1, 2024
1 parent ddabf0b commit 3daaeec
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions longest-repeating-character-replacement/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// TC: O(26 * n) => O(n)
// iterates 26 times at the first for-loop, while loop O(n)
// SC: O(1)
class Solution {
public int characterReplacement(String s, int k) {
int ans = 0;
int n = s.length();
for (char c = 'A'; c <= 'Z'; c++) {
int i = 0, j = 0, replaced = 0;
while (j < n) {
if (s.charAt(j) == c) {
j += 1;
} else if (replaced < k) {
j += 1;
replaced++;
} else if (s.charAt(i) == c) {
i += 1;
} else {
i += 1;
replaced -= 1;
}
ans = Math.max(ans, j - i);
}
}
return ans;
}
}

0 comments on commit 3daaeec

Please sign in to comment.