LinkedHashMapSolution (Super simple!)


  • 0
    D

    This question is quite similar to LRU cache problem. So use of linkedHashMap is natural

    public class Solution {
        int start=0;
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            LinkedHashMap<Character, Integer> map = new LinkedHashMap(2*k, 1f, true) {
                protected boolean removeEldestEntry(Map.Entry entry) {
                    boolean remove = size() > k;
                    if (remove) {
                        start = ((Integer) entry.getValue()) + 1;
                    }
                    return remove;
                }
            };
            
            int ret = 0;
            for (int i=0;i<s.length();i++) {
                Character ch = s.charAt(i);
                map.put(ch, i);
                ret=Math.max(ret, i-start+1);
            }
            return ret;
        }
    }
    

Log in to reply
 

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