-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconcatenated_words.go
74 lines (63 loc) · 1.43 KB
/
concatenated_words.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
type Trie struct {
Children map[string]*Trie // important to make it a pointer to modify the Children.Trie value
End bool
}
func NewTrie() *Trie {
return &Trie{
Children: make(map[string]*Trie),
End: false,
}
}
func addWord(t *Trie, word string) {
var current *Trie = t
for i := 0; i < len(word); i++ {
letter := string(word[i])
if _, ok := current.Children[letter]; !ok {
current.Children[letter] = NewTrie()
}
current = current.Children[letter]
}
current.End = true
}
func searchConcat(root *Trie, word string, index int, count int) bool {
// base case
if index >= len(word) {
return count >= 2
}
var current *Trie = root
for i := index; i < len(word); i++ {
letter := string(word[i])
if _, ok := current.Children[letter]; !ok {
break
}
current = current.Children[letter]
// when we reach the end, 2 choices
// restart or continue
if current.End {
// restart
atRestart := searchConcat(root, word, i+1, count+1)
if atRestart {
return true
} else {
// continue down the branch
continue
}
}
}
return false
}
func findAllConcatenatedWordsInADict(words []string) []string {
var trie *Trie = NewTrie()
for _, word := range words {
addWord(trie, word)
}
var validWords []string = []string{}
for _, word := range words {
isFound := searchConcat(trie, word, 0, 0)
if isFound {
validWords = append(validWords, word)
}
}
return validWords
}