Skip to content

Instantly share code, notes, and snippets.

@murattuzel
Created August 2, 2019 00:49
Show Gist options
  • Save murattuzel/a74721ffe9b0d374cad3f680bb3db25b to your computer and use it in GitHub Desktop.
Save murattuzel/a74721ffe9b0d374cad3f680bb3db25b to your computer and use it in GitHub Desktop.
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