Last active
September 17, 2019 14:30
-
-
Save theodesp/5bb4faa69c3a8f620adee359c770aed2 to your computer and use it in GitHub Desktop.
Find all substrings of string s #go
This file contains 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
/* | |
Observation: To find all substrings of s we have i = 0 til s.length and j = i+1 till s.length and we append each substring s[i:j] to the results. | |
We need to also have a map to check for duplicates. | |
*/ | |
func Substrings(s string) []string { | |
result := []string{} | |
seen := make(map[string]interface{}) | |
for i := 0;i < len(s); i += 1 { | |
for j := i+1; j <= len(s); j += 1 { | |
sub := s[i:j] | |
if _, ok := seen[sub]; !ok { | |
result = append(result, sub) | |
seen[sub] = struct {}{} | |
} | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment