Skip to content

Instantly share code, notes, and snippets.

@btamayo
Created October 6, 2015 05:21
Show Gist options
  • Save btamayo/d8cc7447fce217fabc00 to your computer and use it in GitHub Desktop.
Save btamayo/d8cc7447fce217fabc00 to your computer and use it in GitHub Desktop.
Shortest substring
public String scanString() {
int start = s.length() - 1;
int end = s.length() - 1;
int maxLengthFound = s.length(); // Initial maximum length
System.out.println("end: " + end);
for (int i = 0; i < s.length(); i++) {
System.out.println("Checking substring: " + s.substring(0, i + 1) + ", valid: " + isValid());
if ((i == s.length() - 1) && !isValid()) {
System.out.println("Error: No valid substring exists.");
break;
}
char currChar = s.charAt(i);
if (!map.containsKey(currChar)) {
continue;
}
int count = map.get(currChar);
map.put(currChar, --count);
if (i < start) {
start = i;
}
if (isValid()) {
System.out.println("Start: " + start + ", i: " + i);
System.out.println("Substring: " + s.substring(start, i + 1));
if ((s.substring(start, i + 1)).length() < maxLengthFound) {
maxLengthFound = (s.substring(start, i + 1)).length();
}
// If it's valid AND the current character is a surplus, we can increment the first character
if ((currChar == s.charAt(start)) && map.get(currChar) < 0) {
end = i;
// Increment the start index while it's not a character in the map, or the character it encounters is a surplus
// The closer it gets to the end index (i), the shorter the substring is
// First, add a count to the current character in the map
int cCharCount = map.get(currChar);
map.put(currChar, ++cCharCount);
// cChar should now be 0
// Increment begin index
start++;
// See how far you can move start forward
while (!map.containsKey(s.charAt(start)) || map.get(s.charAt(start)) < 0) {
// If we do encounter a character that's in the map but is a surplus, we should count it
if (map.containsKey(s.charAt(start))) {
int sCharCount = map.get(s.charAt(start));
map.put(s.charAt(start), ++sCharCount);
}
start++;
}
System.out.println("Start Index: " + start);
// s.substring(start, i+1) should be a valid substring
System.out.println(map);
String s1 = s.substring(start, i+1);
System.out.println(s1);
subs.put(s1.length(), s1);
if ((s.substring(start, i + 1)).length() < maxLengthFound) {
maxLengthFound = s1.length();
}
}
}
}
return subs.get(maxLengthFound);
}
public Boolean isValid() {
Boolean isValid = true;
for (Integer n : map.values()) {
if (n <= 0) {
isValid = isValid &= true;
} else {
isValid = isValid &= false;
}
}
return isValid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment