159/340 Longest Substring with At Most 2/K Distinct Characters (Medium/Hard)

Description:

Given a string S, find the length of the longest substring T that contains at most k distinct characters.

Example 1:

Input: S = "eceba" and k = 3
Output: 4
Explanation: T = "eceb"

Example 2:

Input: S = "WORLD" and k = 4
Output: 4
Explanation: T = "WORL" or "ORLD"

Challenge

O(n) time


Solution:

from collections import defaultdict
class Solution:
    """
    @param s: A string
    @param k: An integer
    @return: An integer
    """
    def lengthOfLongestSubstringKDistinct(self, string, k):
        # write your code here
        dic = defaultdict(int)
        length = 0
        ret = 0
        
        for i,s in enumerate(string):
            dic[s] += 1
            length += 1
            while len(dic.keys()) > k:
                cache = string[i-length+1]
                dic[cache] -= 1
                if dic[cache] == 0:
                    dic.pop(cache)
                length -= 1
            ret = max(ret,length)
            
        return ret

Total runtime 1157 ms
Your submission beats 26.40% Submissions!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容