Longest Substring with At Most K Distinct Characters

這道題要求給定一個字符串,然後一個k,求一個最大子串的不重複的字符不大於k的最大子串長度

分析:這道題本質要維護一個窗口,即要維護一個hashmap,key爲字符,value爲窗口內的該字符的個數,然後在窗口擴張過程中,檢查chars[end]是否被包含在map中,或者map的大小是否小於k,如果是直接添加;否則就要轉爲收縮,即start開始收縮,直到到達合適位置

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        HashMap<Character,Integer> maps = new HashMap<>();
        char[] chars = s.toCharArray();
        if(k >= chars.length)
            return chars.length;

        int start = 0,end = k-1;
        int length = end-start;

        for(int i = 0;i<k;i++){
            if(!maps.containsKey(chars[i]))
                maps.put(chars[i],0);

            maps.replace(chars[i],maps.get(chars[i])+1);
        }
        for(int i = k;i<chars.length;i++){
            if(maps.size()<k || maps.containsKey(chars[i])){
                if(!maps.containsKey(chars[i])){
                    maps.put(chars[i],0);
                }
                maps.replace(chars[i],maps.get(chars[i])+1);
                if(++end - start > length)
                    length = end - start;
            }else{//start remove
                while(maps.size() == k && start <= end){
                    int count = maps.get(chars[start]) - 1;
                    if(count == 0){
                        maps.remove(chars[start]);
                    }else{
                        maps.replace(chars[start],count);
                    }
                    start++;
                }
                if(start <= end){
                     maps.put(chars[i],1);
                     end = i;
                }
            }
        }
        return length+1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章