Leetcode - Longest Substring with At Most K Distinct Characters

My code:

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int i = 0;
        int j = 0;
        int maxLen = 0;
        for (; i < s.length(); i++) {
            char curr = s.charAt(i);
            map.put(curr, i);
            if (map.size() > k) {
                int leftMost = Integer.MAX_VALUE;
                for (Character c : map.keySet()) {
                    leftMost = Math.min(leftMost, map.get(c));
                }
                map.remove(s.charAt(leftMost));
                j = leftMost + 1;
            }
            maxLen = Math.max(maxLen, i - j + 1);
        }
        return maxLen;
    }
}

和 Longest Substring with At Most Two Distinct Characters
一个原理。
不赘述了。

Similar Questions#

Minimum Window Substring

Longest Substring with At Most K Distinct Characters

Longest Substring with At Most Two Distinct Characters

Longest Substring Without Repeating Characters

Anyway, Good luck, Richardo! — 09/18/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/8a76feb7deef#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞