Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbb-
bcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb".
//maximum k distict allowed
public class LongestSubstringMostKDisinctChar {
public static void main(String[] args) {
String str = "ddacbbaccdedacebb";
int i = -1;
int j =-1;
Map<Character, Integer> map = new HashMap<>();
int length = 0;
int k = 3;
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 {
break;
}
}
while (j<i){
f2 = true;
j++;
char ch = str.charAt(j);
Integer val = map.get(ch);
if(val>1){
map.put(ch,map.get(ch)-1);
}else{
map.remove(ch);
}
if(map.size()==k){
length = Math.max(length,i-j);
break;
}
}
if(!f1 && !f2){
break;
}
//release
}
System.out.println(length);
}
}
No comments:
Post a Comment