Java Solution Using HashMap and Sliding Window concept


  • 0
    A
    
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
            if(k==0){
                return 0;
            }
            
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            int result=0;
            int i=0;
            int j=0;
            while(j < s.length()) {
                if(map.size() == k && !map.containsKey(s.charAt(j))) {
                    result = Math.max(result, j-i);
                    while(map.size() == k){
                        char c = s.charAt(i);
                        if(map.get(c) == 1){
                            map.remove(c);
                        } else {
                            map.put(c, map.get(c)-1);
                        }
                        i++;
                    }
                }
                char c = s.charAt(j);
                if(!map.containsKey(c)){
                    map.put(c, 1);
                } else {
                    map.put(c, map.get(c)+1);
                }
                j++;
            }
            result = Math.max(result, j-i);
            return result;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.