Leetcode 211. 添加与搜索单词

地址 https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary :
WordDictionary() 初始化词典对象
void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;
否则,返回  false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。
 

示例:
输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]

解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

提示:
1 <= word.length <= 500
addWord 中的 word 由小写英文字母组成
search 中的 word 由 '.' 或小写英文字母组成
最多调用 50000 次 addWord 和 search

解答
类似208,这题同样适用trie前缀树记录和搜索字符串
唯一不同的是,遇到'.'字符,需要遍历搜索该节点下所有可能的后继字符串

class WordDictionary {
public:
	/** Initialize your data structure here. */
	struct NODE {
		char l;
		bool wordFinish;
		struct NODE* next[26];
	};

	struct NODE* root;
	WordDictionary() {
		root = new struct NODE();
	}

	void addWord(string word) {
		struct NODE* curr = root;
		for (int i = 0; i < word.size(); i++) {
			char c = word[i];
			if (curr->next[c - 'a'] == NULL) {
				curr->next[c - 'a'] = new struct NODE();
			}
			curr = curr->next[c - 'a'];
			curr->l = c;
			if (i == word.size() - 1) {
				curr->wordFinish = true;
			}
		}
	}

	bool searchInner(struct NODE* curr, string word, int idx) {
		if (idx >= word.size()) { return false; }
		char c = word[idx];

		if (c == '.') {
			for (int i = 0; i < 26; i++) {
				c = 'a' + i;
				if (curr->next[c - 'a'] != NULL) {
					struct NODE* old = curr;
					curr = curr->next[c - 'a'];
					if (idx == word.size() - 1 && curr->wordFinish == true) return true;
					if (searchInner(curr, word, idx + 1)) return true;

					curr = old;
				}
			}
			return false;
		}
		else {
			if (curr->next[c - 'a'] == NULL) return false;
			else {
				curr = curr->next[c - 'a'];
				if (idx == word.size()-1 && curr->wordFinish == true) return true;
				return searchInner(curr,word,idx+1);
			}
		}
			
		return false;
	}

	bool search(string word) {
		struct NODE* curr = root;
		return searchInner(curr,word,0);
	}
};

我的视频题解空间

作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/15203592.html