Problem Summary
Given a string S and an integer K, find the length of the longest substring T that contains at most K distinct characters.
Solution
We can use two pointers, L and R, to mark the beginning and ending points of the current subsequence. Each time we greedily move R forward by 1, without breaking the rule that the substring contains at most K distinct characters. That is, if and only if the rule would not hold when R is moved forward, we move L forward too.
The time complexity is O(N).
Plus, there are some details with coding. In line 16 of the following code, if we replace the inequality with “r<s.length()”, there will be errors. Because r is of type “int” and s.length() is of type “unsigned int”, r will be converted to type “unsigned int” for the comparison. -1 will be converted to 4294967295, which is the maximum of unsigned int.
Code
|
|