题意
实现词典类 WordDictionary
:
WordDictionary()
初始化词典对象void addWord(word)
将word
添加到数据结构中,之后可以对它进行匹配bool search(word)
如果数据结构中存在字符串与word
匹配,则返回true
;否则,返回false
。word
中可能包含一些'.'
,每个.
都可以表示任何一个字母
思路
.
是通配符 ,所以处理的时候要dfs
处理遇到通配符的情况 枚举每条能走的路
题目给出的框架:
class WordDictionary {
public:
WordDictionary() {
}
void addWord(string word) {
}
bool search(string word) {
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
Code
class WordDictionary {
private:
const int N = 2e5+10;
vector<vector<int>>son;
vector<int>cnt;
int idx=0;
public:
WordDictionary() : son(N,vector<int>(26)),cnt(N) {}
void addWord(string word) {
int p=0;
for(char c:word){
int u=c-'a';
if(son[p][u]==0) son[p][u]=++idx;
p=son[p][u];
}
cnt[p]++;
}
bool search(string word) {
int n=word.size();
function<bool(int,int)>dfs=[&](int p,int i)->bool{
if(i==n) return cnt[p]>0;
if(word[i]=='.'){
for(int j=0;j<26;j++){
if(son[p][j]!=0){
bool flag=dfs(son[p][j],i+1);
if(flag) return 1;
}
}
return 0;
}else{
char c=word[i];
int u=c-'a';
if(son[p][u]!=0){
bool flag=dfs(son[p][u],i+1);
if(flag) return 1;
}
return 0;
}
return 0;
};
return dfs(0,0);
}
};