211. 添加与搜索单词 - 数据结构设计 - 力扣(LeetCode)
两个操作,添加和搜索。
搜索的时候 '.'可以匹配任何字符。
其余的很像LeetCode第 208 题:实现Trie(前缀树)(C++)
但是这儿如果这个字符是 '.'的时候,需要特殊处理,需要遍历成员数组中的每一个位置,只要有一个位置可达终点,就返回true。
class WordDictionary {
public:
struct TrieNode{
bool isEnd = false;
TrieNode* children[26] = {NULL};
};
WordDictionary() : root(new TrieNode) {}
void addWord(string word) {
auto p = root;
for(int i = 0; i < word.size(); ++i){
int idx = word[i] - 'a';
if(p->children[idx] == NULL) p->children[idx] = new TrieNode;
p = p->children[idx];
}
p->isEnd = true;
}
bool search(string word) {
return subSearch(root, word);
}
//从p开始,检索word
bool subSearch(TrieNode *p, string word) {
if(!p) return false;
for(int i = 0; i < word.size(); ++i){
if(word[i] == '.'){
for(int j = 0; j < 26; ++j)
if(subSearch(p->children[j], word.substr(i+1))) return true;//至少有一个可达
return false;
}
int idx = word[i] - 'a';
if(p->children[idx] == NULL) return false;
p = p->children[idx];
}
return p->isEnd;
}
private:
TrieNode *root;
};