Problem 340: Longest Substring with At Most K Distinct Characters
PreviousProblem 3: Longest Substring Without Repeating CharactersNextProblem 239: Sliding Window Maximum
Last updated
Last updated
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] map = new int[128];
int i = 0, j = 0, count = 0, maxLen = 0;
while (j < s.length()) {
if (map[s.charAt(j++)]++ == 0) count++;
if (count > k) {
while (--map[s.charAt(i++)] > 0);
count--;
}
maxLen = Math.max(maxLen, j - i);
}
return maxLen;
}
}/**
* Created by yang on 12/30/16.
*/
public class minWindow {
public static String lengthOfLongestSubstringKDistinct(String s, int k) {
int[] map = new int[128];
int i = 0, j = 0, count = 0, maxLen = 0;
String rst = "";
while (j < s.length()) {
if (map[s.charAt(j++)]++ == 0) count++;
if (count > k) {
while (--map[s.charAt(i++)] > 0) ;
count--;
}
//maxLen = Math.max(maxLen, j - i );
if (j - i > maxLen) {
rst = s.substring(i, j);
maxLen = Math.max(maxLen, j - i);
}
}
return rst;
}
public static void main(String[] args) {
String s = "bbBAbBabbbA";
System.out.println(lengthOfLongestSubstringKDistinct(s, 2));
}
}if (map[s.charAt(j++)]++ == 0) count++;while (--map[s.charAt(i++)] > 0);