Created
April 4, 2019 06:40
-
-
Save Ahmah2009/d7a32cf7ece5d10e33868cc94eb4ad81 to your computer and use it in GitHub Desktop.
472. Concatenated Words leetcode
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
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