题目描述
思路分析
Trie+dfs
采用Trie存储字符串,查找时dfs递归搜索。数据结构设计题还是很有趣的。
代码实现
class WordDictionary {
public:
struct Node{
bool is_end;
Node* son[26];
Node(){
is_end=false;
for(int i=0;i<26;i++) son[i]=NULL;
}
}*root;
WordDictionary() {
root=new Node();
}
void addWord(string word) {
Node* p=root;
for(auto c:word){
int t=c-'a';
if(!p->son[t]) p->son[t]=new Node();
p=p->son[t];
}
p->is_end=true;
}
bool search(string word) {
return dfs(word,0,root);
}
bool dfs(string &word,int k,Node* u){
if(k==word.size()) return u->is_end;
if(word[k]!='.'){
if(u->son[word[k]-'a']) return dfs(word,k+1,u->son[word[k]-'a']);
}
else{
for(int i=0;i<26;i++){
if(u->son[i]){
if(dfs(word,k+1,u->son[i])) return true;
}
}
}
return false;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/