340. Longest Substring with At Most K Distinct Characters解题报告

本文介绍了一种使用哈希映射解决字符串中最大子串问题的方法,该问题要求找到包含最多k个不同字符的最长子串。在Python实现中,通过双指针技巧,当哈希映射内字符种类不超过k时移动右指针,否则移动左指针,并不断更新最长子串长度。最后返回最长子串的长度。示例包括了处理字符串'eceba'和'aa'的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" with length 2.

Constraints:

1 <= s.length <= 5 * 104
0 <= k <= 50

思路:

此题一看是双指针的题。首先思考什么时候移动左指针,什么时候移动右指针,每次移动需要记录点什么。

三个问题倒过来回答。
我用hash map来记录两个指针之间的元素及其个数。
当hash map的大小不超过k的时候,右指针向右移动一个单位。
当hash map的大小超过k的时候,左指针向右移动一个单位。

每当移动右指针,检查hash map的大小,更新最长子字符串长度。
每当移动左指针,检查hash map的大小。

什么是时候停止:
当右指针>=字符串长度时候。

class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        
        hash = {}
        
        
        left, right = 0, 0
        longest = 0
        while right < len(s):
            if len(hash) <= k:
                to_add = s[right]
                if to_add in hash:
                    hash[to_add] += 1
                    
                else:
                    hash[to_add] = 1
                
                if len(hash) <= k:
                    longest = max(longest, right-left+1)
                
                right += 1
                
            else:
                to_sub = s[left]
                left += 1
                
                if hash[to_sub] > 1:
                    hash[to_sub] -= 1
                else:
                    del hash[to_sub]
                    
        
        return longest

2021-08-04 圣荷西, ☀️, 太阳花快开完了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值