Skip to content

Instantly share code, notes, and snippets.

@AlbertoElias
Created April 28, 2014 22:37
Show Gist options
  • Save AlbertoElias/11386106 to your computer and use it in GitHub Desktop.
Save AlbertoElias/11386106 to your computer and use it in GitHub Desktop.
Gets longest substrings formed by two unique characters
import java.util.Arrays.*;
public class LongestSubstring {
public String getLongestSubstring(String s) {
String[] charArray = s.split("(?!^)");
int resStart = 0, resEnd = 0;
String firstChar = charArray[0], secondChar = null;
for (int i = 0, j = 0;i < charArray.length; i++) {
if (secondChar == null && !charArray[i].equals(firstChar)) {
secondChar = charArray[i];
}
if (!charArray[i].equals(firstChar) && !charArray[i].equals(secondChar)) {
if (i-j > resEnd-resStart) {
resStart = j;
resEnd = i;
}
j = i-1;
firstChar = charArray[j];
secondChar = charArray[i];
}
}
return s.substring(resStart, resEnd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment