给定一个字符串,找到最多有k个不同字符的最长子字符串。
Yes
样例
例如,给定 s = "eceba"
, k = 3
,
T 是 "eceb"
,长度为 4
.
挑战
标签
Expand
O(n), n 是所给字符串的长度
相关题目
Expand
解题思路:
利用双指针,以及map实现。
用map记录每一个字符出现的次数,若该字符出现过,则将value加1,若是该字符没有出现过,增加该key,value=1。
在去判断map.size()是否大于k,大于减去slow指针的key所对应的map元素,否则直接计算该slow到fast指针的符合条件的数字。
public class Solution {
/**
* @param s : A string
* @return : The length of the longest substring
* that contains at most k distinct characters.
*/
public int lengthOfLongestSubstringKDistinct(String s, int k) {
// write your code here
if (s == null || s.length() == 0)
return 0;
int slow = 0;
int res = 0;
HashMap<Character, Integer> map = new HashMap<>();
for (int fast = 0; fast < s.length(); fast++) {
char c = s.charAt(fast);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
if(map.size()>k){
char tmp = s.charAt(slow++);
int count = map.get(tmp);
if(count-1>0){
map.put(tmp, count-1);
}else{
map.remove(tmp);
}
}
res = Math.max(res, fast-slow+1);
}
return res;
}
}