Find the longest substring with at most two unique characters(ASCII) in a given string .
We create a set of length 256 to keep the last index from the left. Whenever we reach a new character and count is still less than or equal to 2 we check if the current substring length is greater than the previous result. If it is we update the result as the current longest substring.
public static String longestTwoUnique(String s) {
char str[] = s.toCharArray();
int[] set = new int[256];
Arrays.fill(set, -1);
int i = 0, j = 0;
String res = "";
int count = 0;
while (j < s.length()) {
if (set[str[j]] == -1) {
set[str[j]] = j;
count++;
if (res.length() <= j - i)
res = s.substring(i, j);
if (count > 2) {
count--;
int nextI = set[str[i]];
set[str[i]] = -1;
i = nextI + 1;
}
} else {
set[str[j]] = j;
if (res.length() <= j - i)
res = s.substring(i, j);
}
j++;
}
if (count <= 2 && res.length() <= j - i)
res = s.substring(i, j);
return res;
}
Read full article from Algo Ramblings: Longest substring with 2 unique characters.
We create a set of length 256 to keep the last index from the left. Whenever we reach a new character and count is still less than or equal to 2 we check if the current substring length is greater than the previous result. If it is we update the result as the current longest substring.
public static String longestTwoUnique(String s) {
char str[] = s.toCharArray();
int[] set = new int[256];
Arrays.fill(set, -1);
int i = 0, j = 0;
String res = "";
int count = 0;
while (j < s.length()) {
if (set[str[j]] == -1) {
set[str[j]] = j;
count++;
if (res.length() <= j - i)
res = s.substring(i, j);
if (count > 2) {
count--;
int nextI = set[str[i]];
set[str[i]] = -1;
i = nextI + 1;
}
} else {
set[str[j]] = j;
if (res.length() <= j - i)
res = s.substring(i, j);
}
j++;
}
if (count <= 2 && res.length() <= j - i)
res = s.substring(i, j);
return res;
}
Read full article from Algo Ramblings: Longest substring with 2 unique characters.