Given "abcadcacacaca" and 3, it returns "cadcacacaca".
public class LongestSubstringExactKDistinctElement {
public static void main(String[] args) {
String str = "aabcbcdbca";
int i =-1;
int j =-1;
int length = 0;
int k =2;
Map<Character,Integer> map = new HashMap<>();
while (true){
boolean f1 = false,f2 = false;
//acquire
while (i<str.length()-1){
f1 = true;
i++;
char ch = str.charAt(i);
if(map.containsKey(ch)) {
map.put(ch, map.get(ch)+1);
}else{
map.put(ch,1);
}
if(map.size()==k){
length = Math.max(length,i-j);
}else if(map.size()>k){
break;
}
}
//release
while (j<i){
f2 = true;
j++;
char ch = str.charAt(j);
Integer val = map.get(ch);
if(val==1){
map.remove(ch);
}else{
map.put(ch,map.get(ch)-1);
}
if(map.size()==k){
Math.max(length,i-j);
break;
}else if(map.size()>k){
continue;
}
}
if(!f1 && !f2){
break;
}
}
System.out.println(length);
}
}
No comments:
Post a Comment