340.至多包含K个不同字符的最长子串
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int len = s.length();
if(len <= k){
return len;
}
int left = 0,right = 0;
HashMap<Character,Integer> hashmap = new HashMap<Character,Integer>();
int max_len = k;
while(right < len){
hashmap.put(s.charAt(right),right++);
if(hashmap.size() == k + 1){
int del_idx = Collections.min(hashmap.values());
hashmap.remove(s.charAt(del_idx));
left = del_idx + 1;
}
max_len = Math.max(max_len,right - left);
}
return max_len;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24