码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串

时间:2018-03-10 10:19:58      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:count   ati   else   rac   ring   sts   pytho   python   remove   

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.

159. Longest Substring with At Most Two Distinct Characters 的拓展,159题是最多有2个不同字符,这里是最多有k个不同字符。

解题方法一样,只是把比较不同字符个数时的2换成k。

Java:

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s == null || s.isEmpty() || k < 1) return 0;
        if (s.length() <= k) return s.length();

        int result = k;
        int pre = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);

            while (map.size() > k) {
                char p = s.charAt(pre++);
                int count = map.get(p) - 1;
                if (count == 0) {
                    map.remove(p);
                } else {
                    map.put(p, count);
                }
            }
            result = Math.max(result, i - pre + 1);
        }
        return result;
    }
}

Java:

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
    	if (s == null || s.length() == 0 || k <= 0) {
    		return 0;
    	}
    	HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    	int count = 0;
    	int start = 0;
    	int max = 0;
    	for (int i = 0; i < s.length(); i++) {
    		char c = s.charAt(i);
    		if (map.containsKey(c)) {
    			map.put(c, map.get(c) + 1);
    		} else {
    			map.put(c, 1);
    			while (map.size() > k) {
	    			char rm = s.charAt(start);
	    			int tempCount = map.get(rm);
	    			if (tempCount > 1) {
	    				map.put(rm, tempCount - 1);
	    			} else {
	    				map.remove(rm);
	    			}
	    			start++;
	    			count--;
	    		}
    		}
    		count++;
    		max = Math.max(max, count);
    	}
    	return max;
    }
}

Python:

class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)]
        for i, char in enumerate(s):
            if visited[ord(char)] == 0:
                distinct_count += 1
            visited[ord(char)] += 1
            
            while distinct_count > k:
                visited[ord(s[start])] -= 1
                if visited[ord(s[start])] == 0:
                    distinct_count -= 1
                start += 1
  
            longest = max(longest, i - start + 1)
        return longest

C++:

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        int longest = 0, start = 0, distinct_count = 0;
        array<int, 256> visited = {0};
        for (int i = 0; i < s.length(); ++i) {
            if (visited[s[i]] == 0) {
                ++distinct_count;
            }
            ++visited[s[i]];
            while (distinct_count > k) {
                --visited[s[start]];
                if (visited[s[start]] == 0) {
                    --distinct_count;
                }
                ++start;
            }
            longest = max(longest, i - start + 1);
        }
        return longest;
    }
};

 

类似题目:

[LeetCode] 3.Longest Substring Without Repeating Characters 最长无重复子串

[LeetCode] 159. Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串

 

  

[LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串

标签:count   ati   else   rac   ring   sts   pytho   python   remove   

原文地址:https://www.cnblogs.com/lightwindy/p/8537211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!