Sliding Window
Longest Repeating Character Replacement
DESCRIPTION (inspired by Leetcode.com)
Write a function to find the length of the longest substring containing the same letter in a given string s (consisting of only uppercase English letters), after performing at most k operations in which you can choose any character of the string and change it to any other uppercase English letter. Each operation changes one character at one position, so changing three Bs to As uses 3 operations.
Input:
s = "BBABCCDD" k = 2
Output:
5
Explanation: Replace the 'A' and the first 'C' with 'B' to form "BBBBBCDD". That uses 2 operations, one for each character changed. The longest substring with identical letters is "BBBBB", which has a length of 5.
Explanation
- state: A dictionary mapping each character to the number of times it appears in the current window.
- max_freq: The maximum number of times a single character has appeared in any window so far.
def characterReplacement(s, k):state = {}max_freq = 0max_length = 0start = 0for end in range(len(s)):state[s[end]] = state.get(s[end], 0) + 1max_freq = max(max_freq, state[s[end]])if k + max_freq < end - start + 1:state[s[start]] -= 1start += 1max_length = max(max_length, end - start + 1)return max_length
start
longest repeating character replacement
0 / 12
def characterReplacement(s, k):state = {}max_freq = 0max_length = 0start = 0for end in range(len(s)):state[s[end]] = state.get(s[end], 0) + 1max_freq = max(max_freq, state[s[end]])if k + max_freq < end - start + 1:state[s[start]] -= 1start += 1max_length = max(max_length, end - start + 1)return max_length
max_freq: 3
start: 0 | end: 5
expand window
0 / 9
def characterReplacement(s, k):state = {}max_freq = 0max_length = 0start = 0for end in range(len(s)):state[s[end]] = state.get(s[end], 0) + 1max_freq = max(max_freq, state[s[end]])if k + max_freq < end - start + 1:state[s[start]] -= 1start += 1max_length = max(max_length, end - start + 1)return max_length
max_freq: 4
start: 3 | end: 8
expand window
0 / 5
Solution
def characterReplacement(s, k):state = {}max_freq = 0max_length = 0start = 0for end in range(len(s)):state[s[end]] = state.get(s[end], 0) + 1max_freq = max(max_freq, state[s[end]])if k + max_freq < end - start + 1:state[s[start]] -= 1start += 1max_length = max(max_length, end - start + 1)return max_length
start
longest repeating character replacement
0 / 26
Your account is free and you can post anonymously if you choose.