设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
思路分析:这种大规模的储存单词,比较常用的就是后缀树。
请先翻阅 LeetCode 后缀树
这题就是利用上一题的数据结构存放单词,只是增加对于通配符的处理。
class WordDictionary {
private:
struct TrieNode {
bool isWord;//当前节点为结尾是否是字符串
vector<TrieNode*> children;
TrieNode() : isWord(false), children(26, nullptr) {}
~TrieNode() {
for (TrieNode* child : children)
if (child) delete child;
}
};
TrieNode * trieRoot;//树的根节点
//从str[nowIndex]开始nowPtr搜索(回溯法)
bool myFind(string &str, TrieNode *nowPtr, int nowIndex) {
int strSize = str.size();
if (nowPtr == NULL) {
return false;
}
if (nowIndex >= strSize) {//如果所有的字符都已按顺序匹配完
if (nowPtr->isWord){//需要判断这寻找到的是字符串还是公共前缀
return true;
}
return false;
}
else if (str[nowIndex] != '.') {//如果不是通配符
if (nowPtr->children[str[nowIndex] - 'a'] != NULL) {//如果nowPtr->children有这个字符节点
return myFind(str, nowPtr->children[str[nowIndex] - 'a'], nowIndex + 1);//继续寻找str中的下一个字符
}
return false;
}
else {
//如果是通配符,说明这个可以匹配任意一个字符
for (int i = 0; i < 26; ++i) {//对nowPtr->children的二十六个字符进行穷举
//如果当前匹配成功
if (nowPtr->children[i] != NULL && myFind(str, nowPtr->children[i], nowIndex + 1)) {
return true;
}
}
}
return false;
}
public:
/** Initialize your data structure here. */
WordDictionary() {
trieRoot = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode *ptr = trieRoot;//扫描这棵树,将word插入
//将word的字符逐个插入
for (auto ch : word) {
if (ptr->children[ch - 'a'] == NULL) {
ptr->children[ch - 'a'] = new TrieNode();
}
ptr = ptr->children[ch - 'a'];
}
ptr->isWord = true;//标记为单词
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return myFind(word, trieRoot, 0);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/