class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
HashMap<Character, Integer> map = new HashMap<>();
int start = 0;
int maxLen = 0;
for (int end = 0; end < s.length(); end++) {
if (!map.containsKey(s.charAt(end))) {
map.put(s.charAt(end), 1);
} else {
map.put(s.charAt(end), map.get(s.charAt(end)) + 1);
}
while (map.size() > k) {
map.put(s.charAt(start), map.get(s.charAt(start)) - 1);
if (map.get(s.charAt(start)).equals(0)) {
map.remove(s.charAt(start));
}
start++;
}
maxLen = Math.max(maxLen, end - start + 1);
}
return maxLen;
}
}
LeetCode 340. 至多包含 K 个不同字符的最长子串
最新推荐文章于 2022-12-07 23:58:49 发布