Description
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s = “eceba”
and k = 2,
T is "ece" which its length is 3.
Solution
Slide window, O(n), S(1)
很直观的做法,tricky的地方是,如果当前distinct > k,需要将winStart向后移动,直到某个char完全被清空就行了。注意这里是某个,而非原始winStart指向的char!看这个testcase:
"abacc", k = 2
结果返回的是3,而非2.=。
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if (s == null || s.isEmpty() || k < 1) {
return 0;
}
int[] count = new int[256];
int distinct = 0;
int start = 0;
int maxLen = 0;
for (int end = 0; end < s.length(); ++end) {
char c = s.charAt(end);
if (count[c]++ == 0) {
++distinct;
}
if (distinct > k) {
while (--count[s.charAt(start++)] > 0) { }
--distinct;
}
maxLen = Math.max(end - start + 1, maxLen);
}
return maxLen;
}
}
网友评论