题目:
请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
WordDictionary()初始化词典对象void addWord(word)将word添加到数据结构中,之后可以对它进行匹配bool search(word)如果数据结构中存在字符串与word匹配,则返回true;否则,返回false。word中可能包含一些'.',每个.都可以表示任何一个字母。
算法:
type WordDictionary struct {
Node [26]*WordDictionary
End bool
}
func Constructor() WordDictionary {
return WordDictionary{Node: [26]*WordDictionary{}}
}
func (this *WordDictionary) AddWord(word string) {
node := this
for i := range word {
if node.Node[word[i]-'a'] == nil {
node.Node[word[i]-'a'] = &WordDictionary{Node: [26]*WordDictionary{}}
}
node = node.Node[word[i]-'a']
}
node.End = true
// fmt.Println(node, word)
}
func (this *WordDictionary) Search(word string) bool {
node := this
var backtracking func(index int) bool
backtracking = func(index int) bool {
if node == nil {
return false
}
if index == len(word) {
return node != nil && node.End
}
nodeCopy := node
if word[index] == byte('.') {
for i := range node.Node {
if node.Node[i] != nil {
node = node.Node[i]
if backtracking(index + 1) {
return true
}
node = nodeCopy
}
}
return false
}
if node.Node[word[index] - 'a'] == nil {
return false
}
node = node.Node[word[index] - 'a']
match := backtracking(index + 1)
if match {
return true
}
node = nodeCopy
return false
}
return backtracking(0)
}