You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
Input: s ="ABAB", k =2Output: 4Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
1
2
3
4
5
Input: s ="AABABBA", k =1Output: 4Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
There may exists other ways to achieve this answer too.
classSolution {
publicintcharacterReplacement(String s, int k) {
HashMap<Character, Integer> freq =new HashMap<>(); // frequency mapint l = 0; // left pointerint maxCharCount = 0; // max frequency of any char in windowint ans = 0; // resultfor (int r = 0; r < s.length(); r++) { // right pointerchar c = s.charAt(r);
freq.put(c, freq.getOrDefault(c, 0) + 1);
maxCharCount = Math.max(maxCharCount, freq.get(c));
// Check if changes needed exceed kwhile ((r - l + 1) - maxCharCount > k) {
char leftChar = s.charAt(l);
freq.put(leftChar, freq.get(leftChar) - 1);
l++;
}
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defcharacterReplacement(self, s: str, k: int) -> int:
freq: defaultdict = defaultdict(int) # character frequency in window l: int =0# left pointer max_char_count: int =0# max frequency of any char in window ans: int =0# resultfor r in range(len(s)): # right pointer freq[s[r]] +=1 max_char_count = max(max_char_count, freq[s[r]])
# Check if changes needed exceed kwhile (r - l +1) - max_char_count > k:
freq[s[l]] -=1 l +=1 ans = max(ans, r - l +1)
return ans