211.添加与搜索单词 - 数据结构设计

82 阅读1分钟

题目:
请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 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)
}