211. 添加与搜索单词 - 数据结构设计
思路:前缀树
添加单词,将单词添加到字典树
搜索单词,从字典树的根节点开始搜索,遇到点号,对于所有的子节点进行遍历;如果是字母,判断对应的子节点是否存在
struct TrieNode{
vector<TrieNode*> child;
bool isEnd;
TrieNode(){
child = vector<TrieNode*>(26, nullptr);
isEnd = false;
}
};
void insert(TrieNode* root, const string& word){
TrieNode* node = root;
for(const char& c:word){
if(node->child[c-'a']==nullptr){
node->child[c-'a']=new TrieNode();
}
node=node->child[c-'a'];
}
node->isEnd=true;
}
class WordDictionary {
public:
WordDictionary() {
root=new TrieNode();
}
void addWord(string word) {
insert(root,word);
}
bool search(string word) {
return dfs(root,0,word);
}
bool dfs(TrieNode* root, int index, string& word){
if(root==nullptr) return false;
if(index==word.size()){
return root->isEnd;
}
char ch=word[index];
if(ch>='a'&&ch<='z'){
TrieNode* child=root->child[ch-'a'];
return dfs(child,index+1,word);
}
else{
for(TrieNode* child:root->child){
if(dfs(child,index+1,word))
return true;
}
}
return false;
}
TrieNode* root;
};
时间复杂度 初始化 O(1) 添加单词 O(|S|) S是单词长度 搜索单词 O(|∑|S) ∑是字符集,这道题|∑|=26
空间复杂度 O(|∑|*|T|) |T|是所有添加单词的长度之和