0424-longest-repeating-character-replacement¶
Try it on leetcode
Description¶
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.
Example 1:
Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input: s = "AABABBA", k = 1 Output: 4 Explanation: 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.
Constraints:
1 <= s.length <= 105sconsists of only uppercase English letters.0 <= k <= s.length
Solution(Python)¶
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# s = "ABAB", k = 2 4
# s = "AABABBA", k = 1 4
#
# l r = 0 0
# cur A
# cnt = 0
# i = 0 cnt = 1
# i =2 B != A; j > 0; cnt +=1
# i =3 ; Cnt = 3
# i =4 B != A; j > 0; cnt 4
#
# s = "AABABBA", k = 1 4
#
# r =0 l = 0
# cur = A
#
# r =1 A == A
#
# r =2 A!=B ; 1 > 0; k = 0
#
# r =3 A ==A
# r = 4 A! B 1 == 0
# ans r - l
# l = 4
# k =k
# cur = None
# l= 5
# cur = B
# Time complexity: O(n
# Space complexity: O(m)
start = 0
frequency_map = {}
max_frequency = 0
longest_substring_length = 0
for end in range(len(s)):
frequency_map[s[end]] = frequency_map.get(s[end], 0) + 1
max_frequency = max(max_frequency, frequency_map[s[end]])
is_valid = (end + 1 - start - max_frequency <= k)
if not is_valid:
frequency_map[s[start]] -= 1
start += 1
longest_substring_length = end + 1 - start
return longest_substring_length