15~ line 42ms JAVA solution using HashMap


  • 0
    M
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int low = 0;
        int ret = 0;
        for (int i=0; i<s.length(); i++) {
            map.put(s.charAt(i), i);
            if (map.size() > k) {
                low = Collections.min(map.values()) + 1;
                map.remove(s.charAt(low-1));
            }
            ret = Math.max(ret, i - low + 1);
        }
        return ret;
    }

Log in to reply
 

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