Learn DSA
Depth-First Search
Greedy Algorithms
Sliding Window
Longest Repeating Character Replacement
medium
DESCRIPTION (credit Leetcode.com)
Write a function to find the length of the longest substring containing the same letter in a given string s, 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.
Input:
Output:
Explanation: Replace the first 'A' and 'C' with 'B' to form "BBBBBCCDD". The longest substring with identical letters is "BBBBB", which has a length of 5.
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
"Write a function that takes a string `s` and an integer `k`, and returns the length of the longest substring that can be obtained by replacing at most `k` characters with any other character so that all the characters in the substring are the same."
Run your code to see results here
Have suggestions or found something wrong?
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_count: 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_count: 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
Login to track your progress
Your account is free and you can post anonymously if you choose.