Skip to content

Instantly share code, notes, and snippets.

@Ahmah2009
Created April 4, 2019 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ahmah2009/d7a32cf7ece5d10e33868cc94eb4ad81 to your computer and use it in GitHub Desktop.
Save Ahmah2009/d7a32cf7ece5d10e33868cc94eb4ad81 to your computer and use it in GitHub Desktop.
472. Concatenated Words leetcode
func findAllConcatenatedWordsInADict(words []string) []string {
res:= []string{}
mp:= make(map[string]int)
for _, word := range words {
mp[word] = 1
}
for _, word := range words {
delete(mp, word)
c:=breakWord(word, mp)
if c >1 {
res = append(res, word)
} else if c == 0 {
mp[word] = 1
}
}
return res
}
func breakWord(word string, mp map[string]int) int {
if _, ok := mp[word]; ok {
return mp[word]
}
for i:=1; i < len(word); i++ {
str:= word[0:i]
_, ok := mp[str]
if ok && mp[str] > 0 {
c1 := mp[str]
c2 := breakWord(word[i:], mp)
if c2 > 0 {
mp[word] = c1 + c2
return c1 + c2
}
}
}
mp[word] = 0
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment