-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathLongest_Repeating_Character_Replacement.java
36 lines (31 loc) · 1.33 KB
/
Longest_Repeating_Character_Replacement.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//Leetcode 424. Longest Repeating Character Replacement
//Question - https://leetcode.com/problems/longest-repeating-character-replacement/
class Solution {
public int characterReplacement(String s, int k) {
//number of characters that can be replaced in a given window is
//charsToBeReplaced = length Of Window - frequency Of Most Frequent Letter In Window
//if charsToBeReplaced <= k then the window is valid - else window in invalid and we need to slide 'start' to right
HashMap<Character,Integer> freqTable = new HashMap<>();
int start = 0;
int len = 0;
int maxCount = 0;
int charsToReplace = 0;
for(int end = 0 ; end < s.length() ; end++){
char endChar = s.charAt(end);
int freq = freqTable.getOrDefault(endChar,0);
freq++;
freqTable.put(endChar,freq);
maxCount = Math.max(maxCount, freq);
charsToReplace = end - start - maxCount + 1;
if(charsToReplace>k){
char startChar = s.charAt(start);
freq = freqTable.get(startChar);
freq--;
freqTable.put(startChar,freq);
start++;
}
len = Math.max(len, end-start+1);
}
return len;
}
}