211. 添加与搜索单词 - 数据结构设计
class WordDictionary {
public:
struct Node{
Node *node[26];
bool is_end;
Node()
{
is_end=false;
for(int i=0;i< 26;i++)
{
node[i]=NULL;
}
}
};
Node *root;
WordDictionary() {
root =new Node();
}
void addWord(string word) {
auto p = root;
for(auto c : word)
{
int i = c -'a';
if(!p->node[i]) p->node[i] =new Node();
p=p->node[i];
}
p->is_end =true;
}
bool search(string word) {
return dfs(root,word,0);
}
bool dfs(Node * root ,string & s ,int i)
{
if(i == s.size()) return root->is_end;
if(s[i]!='.')
{
int n = s[i] - 'a';
if(!root->node[n]) return false;
return dfs(root ->node[n] , s, 1+i);
}else
{
for(int j=0 ;j < 26;j++)
{
if(root->node[j] &&dfs(root ->node[j] , s, 1+i))
return true;
}
return false;
}
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60