In order to understand the advanced algorithm concepts like greedy methods and dynamic programming, one first need to be well versed in recursion.
I am relatively new to
@Test
public void testStrings() {
TreeSet<String> finalTree = getSubStringsOf("STACK");
for(String subString : finalTree){
System.out.println(subString);
}
}
public TreeSet<String> getSubStringsOf(String stringIn) {
TreeSet<String> stringOut = new TreeSet<String>();
if (stringIn.length() == 1) {
stringOut.add(stringIn);
return stringOut;
} else {
for (int i = 1; i < stringIn.length() ; i++) {
String stringBefore = stringIn.substring(0, i);
String stringAfter = stringIn.substring(i);
stringOut.add(stringBefore);
stringOut.add(stringAfter);
stringOut.addAll(getSubStringsOf(stringBefore));
stringOut.addAll(getSubStringsOf(stringAfter));
}
return stringOut;
}
}
I don't know if you need explanation. You split the string in two every time it's possible. Cat is thus split into CA,T and C,AT, you add them to your list of substring, then look for every substring of these substrings. If the String is a single character, you add the single character to your tree.
EDIT: this is the output for STACK:
A
AC
ACK
C
CK
K
S
ST
STA
STAC
T
TA
TAC
TACK
EDIT again: As you can see, every time you run the method subString,you'll use it twice inside it, except if it's a single character String. Thus the complexity is O(n²). For 'STACK', the program is 0.200 ms long, for "STACKSTACKSTACK" (3 times stack) is 2seconds, for "STACKSTACKSTACKSTACKSTACK" is theoritically 2^10 times more, thus 2000 seconds.