###### LeetCode211：Add and Search Word - Data structure design

Design a data structure that supports the following two operations:

bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

search(“b..”) -> true
Note:
You may assume that all words are consist of lowercase letters a-z.

Trie这种数据结构可以很方便的实现字符串的查找，它的时间复杂度只有O(L)，根据最下面的提示单词中只有a-z的小写字母这个提示也可以想到使用Trie。

runtime:100ms

class WordDictionary {
public:
class TrieNode
{
public:
TrieNode * edges[26];//子节点
bool end;//标示是否有以这个节点结尾的字符串
TrieNode(){
for(int i=0;i<26;i++)
{
edges[i]=NULL;
}
end=false;
}
};

class Trie
{
public:
Trie(){
root=new TrieNode();
}
//添加单词使用循环实现，也可以使用递归，前面创建Trie树即使用的是递归
{
if(word.empty())
return ;

TrieNode * node=root;
int pos=0;
while(pos<word.size())
{
int char_code=word[pos]-'a';
if(node->edges[char_code]!=NULL)
{
node=node->edges[char_code];
pos++;
}
else
{
node->edges[char_code]=new TrieNode();
node=node->edges[char_code];
pos++;
}
}
node->end=true;
}

//搜索使用递归实现，要是没有'.'使用循环也很容易实现，但是加上限制条件后使用递归更容易一些
bool search(string &word,int pos,TrieNode * node)
{
if(word.empty()&&node->end)
return true;

int char_code=word[pos]-'a';
if(pos==word.size()&&node->end)
return true;

if(char_code=='.'-'a')
{
for(int i=0;i<26;i++)
if(node->edges[i]!=NULL&&search(word,pos+1,node->edges[i]))
return true;
}
else
{
if(node->edges[char_code]!=NULL)
return search(word,pos+1,node->edges[char_code]);
}
}
TrieNode * root;

};

// Adds a word into the data structure.
}

// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return trie.search(word,0,trie.root);
}

private:
Trie trie;
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.search("pattern");

#### leetcode 211: Add and Search Word - Data structure design

2015-05-19 06:12:01

#### leetcode211 一点心得

2015-07-24 00:17:04

#### leetcode.211. Add and Search Word - Data structure design字典树

2016-05-11 15:21:56

#### LeetCode 211. Add and Search Word - Data structure design

2015-08-10 10:50:13

#### Leetcode 211. Add and Search Word - Data structure design

2017-02-10 05:33:04

#### leetcode 211: Add and Search Word - Data Structure Design

2015-08-27 12:02:26

#### 面试笔试杂项积累-leetcode 211-215

2016-02-11 22:49:52

#### <em>LeetCode</em>最全代码

2018年05月07日 00:00

#### [leetcode] 211. Add and Search Word - Data structure design 解题报告

2016-03-28 10:02:18

#### Leetcode 211 Add and Search Word - Data structure design

2015-08-17 18:08:54

## 不良信息举报

LeetCode211：Add and Search Word - Data structure design