Longest Substring with At Most K Distinct Characters

Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains k unique character is "bcbbbbcccb".

分析:

用hashmap记录每个character从start到当前位置出现的次数,如果第k + 1个character出现, 更新maxLength,我们需要把左边的pointer(start) 往右移,直到从start到current之间只有K个character.

 public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null) return ;
if (s.length() <= k) return s.length(); int begin = , end = ;
Map<Character, Integer> map = new HashMap<>();
int tempMaxLength = Integer.MIN_VALUE; while (end < s.length()) {
map.put(s.charAt(end), map.getOrDefault(s.charAt(end), ) + );
while (map.size() > k) {
if (map.get(s.charAt(begin)) == ) {
map.remove(s.charAt(begin));
} else {
map.put(s.charAt(begin), map.get(s.charAt(begin)) - );
}
begin++;
}
tempMaxLength = Math.max(tempMaxLength, end - begin + );
end++;
}
return tempMaxLength;
}
}
上一篇:数据库Mark.2


下一篇:js控制文本框输入数字和小数点等