Created
April 28, 2014 22:37
-
-
Save AlbertoElias/11386106 to your computer and use it in GitHub Desktop.
Gets longest substrings formed by two unique characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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