Skip to content

Commit

Permalink
Create 0211-design-add-and-search-words-data-structure.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AP-Repositories authored Jan 1, 2023
1 parent 0cb22b5 commit d04ef97
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions go/0211-design-add-and-search-words-data-structure.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
type TrieNode struct {
children map[byte]*TrieNode
word bool
}

type WordDictionary struct {
root *TrieNode
}


func Constructor() WordDictionary {
return WordDictionary{root: &TrieNode{children: make(map[byte]*TrieNode)}}
}


func (this *WordDictionary) AddWord(word string) {
cur := this.root
for c := 0; c < len(word); c++ {
if _, ok := cur.children[word[c]]; !ok {
cur.children[word[c]] = &TrieNode{children: make(map[byte]*TrieNode)}
}
cur = cur.children[word[c]]
}
cur.word = true
}


func (this *WordDictionary) Search(word string) bool {
var dfs func(int, *TrieNode) bool
dfs = func(j int, root *TrieNode) bool {
cur := root

for i := j; i < len(word); i++ {
c := word[i]
if c == '.' {
for _, child := range cur.children {
if dfs(i + 1, child) {
return true
}
}
return false
} else {
if _, ok := cur.children[c]; !ok {
return false
}
cur = cur.children[c]
}
}
return cur.word
}

return dfs(0, this.root)
}

0 comments on commit d04ef97

Please sign in to comment.