Simple Java Solution


  • 0
    K

    public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
    if(k == 0) return 0;
    Map<Character, Integer> distinct = new HashMap();
    Queue<Character> queue = new LinkedList();
    int size =0; int maxSize = 0;
    for(Character c : s.toCharArray()) {
    if(distinct.get(c) == null) {
    distinct.put(c,1);
    }
    else {
    distinct.put(c,distinct.get(c)+1);
    }

            queue.add(c);
            if(distinct.size() <= k){
                ++size;
                if(size > maxSize){
                    maxSize = size;
                }
            }
            else {
                while(distinct.size() > k) {
                    Character temp = queue.poll();
                    distinct.put(temp, distinct.get(temp)-1);
                    if(distinct.get(temp) == 0) {
                        distinct.remove(temp);
                    }
                    
                }
                size = queue.size();
            }
        }
        
        return maxSize;    
    }
    

    }


Log in to reply
 

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