Skip to content

Commit e6779ca

Browse files
committed
add: LongestUniformSubstringAfterReplacements
1 parent 1063e32 commit e6779ca

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class LongestUniformSubstringAfterReplacements {
5+
public int longestUniformSubstringAfterReplacements(String s, int k) {
6+
Map<Character, Integer> freqs = new HashMap<>();
7+
int highestFreq = 0;
8+
int maxLen = 0;
9+
int left, right;
10+
left = right = 0;
11+
while (right < s.length()) {
12+
// Update the frequency of the character at the right pointer
13+
// and the highest frequency for the current window.
14+
freqs.put(s.charAt(right), freqs.getOrDefault(s.charAt(right), 0) + 1);
15+
highestFreq = Math.max(highestFreq, freqs.get(s.charAt(right)));
16+
// Calculate replacements needed for the current window.
17+
int numCharsToReplace = (right - left + 1) - highestFreq;
18+
// Slide the window if the number of replacements needed exceeds
19+
// 'k'. The right pointer always gets advanced, so we just need
20+
// to advance 'left'.
21+
if (numCharsToReplace > k) {
22+
// Remove the character at the left pointer from the hash map
23+
// before advancing the left pointer.
24+
freqs.put(s.charAt(left), freqs.get(s.charAt(left)) - 1);
25+
left++;
26+
}
27+
// Since the length of the current window increases or stays the
28+
// same, assign the length of the current window to 'maxLen'.
29+
maxLen = right - left + 1;
30+
// Expand the window.
31+
right++;
32+
}
33+
return maxLen;
34+
}
35+
}

0 commit comments

Comments
 (0)