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 最多有两个不同字符的最长子串

All LeetCode Questions List 题目汇总

  

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

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

    Given a string s , find the length of the longest substring t  that contains at most 2 distinct char ...

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

    Given a string S, find the length of the longest substring T that contains at most two distinct char ...

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

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

  4. 【LeetCode】Longest Substring with At Most Two Distinct Characters (2 solutions)

    Longest Substring with At Most Two Distinct Characters Given a string, find the length of the longes ...

  5. [leetcode]159. Longest Substring with At Most Two Distinct Characters至多包含两种字符的最长子串

    Given a string s , find the length of the longest substring t  that contains at most 2 distinct char ...

  6. ✡ leetcode 159. Longest Substring with At Most Two Distinct Characters 求两个字母组成的最大子串长度 --------- java

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

  7. leetcode[159] Longest Substring with At Most Two Distinct Characters

    找到最多含有两个不同字符的子串的最长长度.例如:eoeabc,最长的是eoe为3,其他都为2. 思路: 用p1,p2表示两种字符串的最后一个出现的下标位置.初始p1为0. p2为-1.start初始化 ...

  8. [leetcode]340. Longest Substring with At Most K Distinct Characters至多包含K种字符的最长子串

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

  9. LeetCode 340. Longest Substring with At Most K Distinct Characters

    原题链接在这里:https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ 题目: Give ...

随机推荐

  1. ACAG 0x02-8 非递归实现组合型枚举

    ACAG 0x02-8 非递归实现组合型枚举 之所以专门来写这道题的博客,是因为感觉从最根本处了解到了递归的机器实现. 主要的就是两个指令--Call和Ret. Call指令会将返回地址入栈(系统栈) ...

  2. SD介绍

    1. 介绍 MMC,MultiMediaCard,即多媒体卡,是一种非易失性存储器件,有7pin,目前已基本被SD卡代替 eMMC,Embedded Multimedia Card,内嵌式存储器,以B ...

  3. python开发总结

    1.思维缜密的编程逻辑 2.满足明确的目的需求 3.运用现成的轮子加以改造 4.学会装饰自己的程序 5.化繁为简 6.多用配置文件作为入口 7.注意扩展兼容

  4. html5添加视频为背景自动播放

    客户想做个打开官网自动播放一段视频,楼主使用了video标签,即下面的代码:: 于是我在video标签上添加了属性 autoplay=“autoplay” loop=“loop” 然而通过地址栏进去的 ...

  5. tensorflow API _ 3 (tf.train.polynomial_decay)

    学习率的三种调整方式:固定的,指数的,多项式的 def _configure_learning_rate(num_samples_per_epoch, global_step): "&quo ...

  6. width: calc(100% - 80px); 屏幕自适应方法

    width: calc(100% - 80px); 屏幕自适应方法

  7. 2019.12.11 java练习

    class Demo01 { public static void main(String[] args) { //数组求最大值 int[] arr={1,2,3,4,5,6,7,8,9}; int ...

  8. 认识Nodejs

    一.概念 ①JavaScript运行环境:Node.js不是一门语言,不是库也不是框架,是一个JavaScript运行环境,简单点来讲就是Node.js可以解析执行JavaScript代码,也就是说J ...

  9. 洛谷 P2918 [USACO08NOV]买干草Buying Hay 题解

    P2918 [USACO08NOV]买干草Buying Hay 题目描述 Farmer John is running out of supplies and needs to purchase H ...

  10. 55、Spark Streaming:updateStateByKey以及基于缓存的实时wordcount程序

    一.updateStateByKey 1.概述 SparkStreaming 7*24 小时不间断的运行,有时需要管理一些状态,比如wordCount,每个batch的数据不是独立的而是需要累加的,这 ...