Created
August 2, 2019 00:49
-
-
Save murattuzel/a74721ffe9b0d374cad3f680bb3db25b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
private int shortestSubstring(String s) { // "dabbcabcd", "bcaacbc", "bab" | |
// for 'dabbcabcd' there is 4 unique letters, so shortest substring can be minimum 4 letter length. if not, | |
// we need to increase that length and keep searching. | |
List<String> letters = new ArrayList<>(); | |
for (char each : s.toCharArray()){ | |
String letter = String.valueOf(each); | |
if (!letters.contains(letter)) { | |
letters.add(letter); | |
} | |
} | |
int minLength = letters.size(); | |
int maxLength = s.length(); | |
Log.d(TAG, "minLength: " + minLength); | |
Log.d(TAG, "maxLength: " + maxLength); | |
for (int currentLength = minLength; currentLength <= maxLength; currentLength++) { | |
int substringSize = maxLength - currentLength + 1; | |
for (int j = 0; j < substringSize; j++) { | |
String substring = s.substring(j, j + currentLength); | |
boolean isFound = isSubstringContainAllLetters(letters, substring); | |
if (isFound) { | |
Log.d(TAG, substring + " is a substring that contains all the characters in s. Length: " + currentLength); | |
return currentLength; | |
} | |
} | |
} | |
return maxLength; | |
} | |
private boolean isSubstringContainAllLetters(List<String> letters, String substring) { | |
for (String letter : letters) { | |
if (!substring.contains(letter)) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment