美文网首页
[LeetCode 340] Longest Substring

[LeetCode 340] Longest Substring

作者: 灰睛眼蓝 | 来源:发表于2019-08-02 15:57 被阅读0次

Given a string, find the length of the longest substring T that contains at most k distinct characters.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s == null || s.length () == 0 || k == 0)
            return 0;
        
        Map<Character, Integer> tracker = new HashMap<> ();
        int start = 0;
        int end = 0;
        int maxLen = 0;
        
        while (end < s.length ()) {
            char currentCh = s.charAt (end);
            int freq = tracker.getOrDefault (currentCh, 0) + 1;
            tracker.put (currentCh, freq);
            
            if (tracker.size () <= k) {
                maxLen = Math.max (maxLen, end - start + 1);
                end++;
                continue;
            }
            
            while (start <= end && tracker.size () > k) {
                char startCh = s.charAt (start);
                freq = tracker.get (startCh) - 1;
                if (freq == 0) {
                    tracker.remove (startCh);
                } else {
                    tracker.put (startCh, freq);
                }
                
                start ++;
            }
            end ++;
        }
        
        return maxLen;
    }
}

相关文章

网友评论

      本文标题:[LeetCode 340] Longest Substring

      本文链接:https://www.haomeiwen.com/subject/lywldctx.html