Interview Questions

Longest substring with k distinc

2016-03-26  本文已影响55人  宋翰要长肉

Longest substring with k distinct characters

Algorithm

Code

public int lengthOfLongestSubstringKDistinct(String s, int size) {
        char[] sArray = s.toCharArray();
        Map<Character, Integer> map = new HashMap<Character, Integer>(); // key is character, value is its count
        int localLen = 0;
        int maxLen = 0;
        int start = 0;
        for (int i = 0; i < s.length(); i++) {
            char key = sArray[i];
            if (map.containsKey(sArray[i])) {
                int newCount = map.get(key) + 1;
                map.put(key, newCount);
            } else {
                map.put(key, 1);
                if (map.size() > size) {
                    localLen = i - start;
                    if (localLen > maxLen) {
                        maxLen = localLen;
                    }
                    while (map.size() > size) {
                        char preKey = sArray[start];
                        int count = map.get(preKey) - 1;
                        if (count == 0) {
                            map.remove(preKey);
                        } else {
                            map.put(preKey, count);
                        }
                        start++;
                    }
                }
            }
        }
        localLen = sArray.length - start;
        if (localLen > maxLen) {
            maxLen = localLen;
        }
        return maxLen;
    }

Complexity

上一篇下一篇

猜你喜欢

热点阅读