340. Longest Substring with At Most K Distinct Characters

Description

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

For example, Given s = “eceba” and k = 2,

T is "ece" which its length is 3.

Solution

Slide window, O(n), S(1)

很直觀的做法,tricky的地方是,如果當(dāng)前distinct > k,需要將winStart向后移動(dòng),直到某個(gè)char完全被清空就行了。注意這里是某個(gè),而非原始winStart指向的char!看這個(gè)testcase:

"abacc", k = 2

結(jié)果返回的是3,而非2.=。

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s == null || s.isEmpty() || k < 1) {
            return 0;
        }
        
        int[] count = new int[256];
        int distinct = 0;
        int start = 0;
        int maxLen = 0;
        
        for (int end = 0; end < s.length(); ++end) {
            char c = s.charAt(end);
            if (count[c]++ == 0) {
                ++distinct;
            }
            
            if (distinct > k) {
                while (--count[s.charAt(start++)] > 0) { }
                --distinct;
            }
            
            maxLen = Math.max(end - start + 1, maxLen);
        }
        
        return maxLen;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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