Longest substring with k distinct characters

Longest substring with k distinct characters

Algorithm

  • traverse the input string from first character to last character.
  • at first the substring start at index 0.
  • we increase the length of substring by one character.
  • when the number of distinct characters in the substring is greater than input number.
  • we find the new start index that make the number of distinct characters in the new substring is equal to input number and continue increase the length of new substring.

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

  • time complexity: O(N)
    • traverse each characters in the input string
    • each character is put in map once and removed from map once
  • space complexity: O(K)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一 依稀记得,好像是从大二开始,我就习惯性的口腔溃疡,跟这个相关的一个概念是“上火“。 这个词在现代汉语词典中解释...
    光影的故事阅读 2,523评论 0 0
  • "沙子是废物,水泥也是废物,但他们混在一起是混凝土,就是精品;大米是精品,汽油也是精品,但他们混在一起就是废物。是...
    7381d9e0c63c阅读 1,405评论 0 0
  • 不久前,刚刚步入婚姻的围墙的我,曾因为应接不暇的琐事,而爆发一次次激烈的争吵,吵到身心俱疲,不止一次感到这段关...
    乖喵喵爱做梦阅读 2,498评论 1 1
  • 不管你多么优秀,遇到讨厌你的人,你就是没用。 不管你多么真诚,遇到爱计较的人,你就是无情。 不管你有多单纯,遇到复...
    灵活摆渡2阅读 2,532评论 0 0
  • 中午因为心情不好,对着冰冰吼了几句。事后觉得很后悔,因为我意识到:孩子并没错,是我自己遇到的其他事情让我烦心、产生...
    珠海兔子阅读 5,603评论 0 1

友情链接更多精彩内容