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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值