Longest Repeating Character Replacement

Intuition

The problem involves finding the length of the longest substring containing the same letter that can be obtained by changing at most k characters. The idea is to use a sliding window approach to keep track of the count of characters within the window and the maximum count of a single character. The goal is to maximize the length of the valid substring.

Approach

The provided solution uses a sliding window with two pointers, left and right, to iterate through the string and maintain the count of characters within the window.

Initialize the pointers left and right to 0.
Initialize a dictionary char_count to keep track of the count of each character within the current window.
Initialize variables max_length and max_count to store the maximum length of the valid substring and the maximum count of a single character, respectively.
Iterate through the string using the right pointer:
Update the count of the current character in the char_count dictionary.
Update the max_count with the maximum count of a single character within the window.
Check if the number of replacements needed (the total characters in the window minus the maximum count) is more than k. If so, move the left pointer to the right and update the count accordingly.
Update the max_length with the maximum length of the valid substring.
Move the right pointer to the next character.
Return the maximum length.

Complexity

  • Time complexity:

The time complexity of this solution is O(n), where n is the length of the input string s. The sliding window approach allows for a single pass through the string.

  • Space complexity:

The space complexity is O(1) because the dictionary char_count is limited to the number of unique characters in the alphabet.

Code

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        left, right = 0, 0
        char_count = {}
        max_length = 0
        max_count = 0

        while right < len(s):
            if s[right] not in char_count:
                char_count[s[right]] = 1
            else:
                char_count[s[right]] += 1

            max_count = max(max_count, char_count[s[right]])

            # Check if the number of replacements needed is more than k
            if (right - left + 1 - max_count) > k:
                char_count[s[left]] -= 1
                left += 1

            # Update the maximum length of the valid substring
            max_length = max(max_length, right - left + 1)
            right += 1

        return max_length

你可能感兴趣的:(leetcode算法学习,python)