Skip to content

Commit cdba760

Browse files
committed
Add longest repeating char replacement solution
1 parent d07aa46 commit cdba760

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
//Sliding window: TC:O(n) SC: O(1)
2+
package java1.algorithms.strings;
3+
4+
public class longestRepeatingCharReplacement {
5+
private static int longestCharReplacement(String str, int target) {
6+
int[] charCount = new int[26];
7+
int maxLength = 0;
8+
int maxCharFrequency = 0;
9+
int left =0;
10+
11+
for(int right = 0; right < str.length(); right++) {
12+
maxCharFrequency = Math.max(maxCharFrequency, ++charCount[str.charAt(right) - 'A']);
13+
while((right - left + 1 - maxCharFrequency) > target) {
14+
charCount[str.charAt(left) - 'A']--;
15+
left++;
16+
}
17+
maxLength = Math.max(maxLength, right-left+1);
18+
}
19+
return maxLength;
20+
}
21+
22+
public static void main(String[] args) {
23+
String str = "AAABABBAA";
24+
System.out.println(longestCharReplacement(str, 2));
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//Sliding window: TC:O(n) SC: O(1)
2+
function longestCharReplacement(str, target) {
3+
let charFrequency = new Array(26).fill(0);;
4+
let maxLength = 0, maxFrequency = 0;
5+
let left = 0;
6+
7+
for(let right = 0; right < str.length; right++) {
8+
maxFrequency = Math.max(maxFrequency, ++charFrequency[str.charCodeAt(right) - "A".charCodeAt(0)]);
9+
while((right-left+1-maxFrequency) > target) {
10+
charFrequency[str.charCodeAt(left) - "A".charCodeAt(0)]--;
11+
left++;
12+
}
13+
maxLength = Math.max(maxLength, right-left+1);
14+
}
15+
return maxLength;
16+
}
17+
18+
let str1 = "AAABABBAA";
19+
console.log(longestCharReplacement(str1, 2));
20+
let str2 = "BBBB";
21+
console.log(longestCharReplacement(str2, 2));

0 commit comments

Comments
 (0)