340. 至多包含 K 个不同字符的最长子串
给定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Map;
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.length() == 0) {
return 0;
}
int[] cnt = new int[256];
int sum = 0;
int ret = 0;
int left = 0, right = 0;
while (right < s.length()) {
cnt[s.charAt(right)]++;
if (cnt[s.charAt(right)] == 1) {
sum++;
while (sum > k) {
cnt[s.charAt(left)]--;
if (cnt[s.charAt(left++)] == 0) {
sum--;
}
}
}
ret = Math.max(ret, right - left + 1);
right++;
}
ret = Math.max(ret, s.length() - left);
return ret;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号