美文网首页
340. Longest Substring with At M

340. Longest Substring with At M

作者: Nancyberry | 来源:发表于2018-06-10 01:54 被阅读0次

    Description

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

    For example, Given s = “eceba” and k = 2,

    T is "ece" which its length is 3.

    Solution

    Slide window, O(n), S(1)

    很直观的做法,tricky的地方是,如果当前distinct > k,需要将winStart向后移动,直到某个char完全被清空就行了。注意这里是某个,而非原始winStart指向的char!看这个testcase:

    "abacc", k = 2

    结果返回的是3,而非2.=。

    class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            if (s == null || s.isEmpty() || k < 1) {
                return 0;
            }
            
            int[] count = new int[256];
            int distinct = 0;
            int start = 0;
            int maxLen = 0;
            
            for (int end = 0; end < s.length(); ++end) {
                char c = s.charAt(end);
                if (count[c]++ == 0) {
                    ++distinct;
                }
                
                if (distinct > k) {
                    while (--count[s.charAt(start++)] > 0) { }
                    --distinct;
                }
                
                maxLen = Math.max(end - start + 1, maxLen);
            }
            
            return maxLen;
        }
    }
    

    相关文章

      网友评论

          本文标题:340. Longest Substring with At M

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