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!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容