Just use two for-loops:
generate substrings(string): for start in [0,1,...,string.length-1]: for end in [start,...,string.length-1]: yield string[start...end]
You can also do this with two for-loops:
generate substrings(string): for substringLength in [1,2,...,string.length]: for start in range [0,1,...,string.length-substringLength]: yield string[start...(start+substringLength-1)] yield ""
You probably want to include the empty string ""
in the returned sequence, since it is a substring of all strings.
You also need to consider whether repeating a repeating string is permissible several times (for example, do you return "ABA" twice as a substring of "ABABA"?). If the answer is no, just create a hash table called alreadyYielded
, and whenever you give in, abort if you already gave a row, otherwise add a value to the hash table if you see it again. For instance:
seen = new HashTable() ... substring = string[...] if substring not in seen: seen.add(substring) yield substring ...
source share