您的位置:首页 > 其它

211. Add and Search Word - Data structure design

2016-05-26 16:07 281 查看
Design a data structure that supports the following two operations:
void addWord(word)
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:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true


Note:

You may assume that all words are consist of lowercase letters
a-z
.
题意:设计一种数据结构满足能够快速添加和查询单词。
思路:字典树+递归查询。

class TrieNode{
public:
TrieNode* next[26];
bool isword;
TrieNode(){
isword = false;
memset(next, 0, 26 * sizeof(TrieNode*));
}
};

class WordDictionary {
public:
WordDictionary(){
root = new TrieNode();
}
// Adds a word into the data structure.
void addWord(string word) {
TrieNode* level = root;
int index = 0;
while (index < word.size()){
int i = word[index] - 'a';
if (level->next[i] == NULL){
level->next[i] = new TrieNode();
}
level = level->next[i];
index++;
}
level->isword = true;
}

// 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 search(word, root);
}
bool search(string word, TrieNode* node){
if (word.empty()){
return node->isword;
}
TrieNode* level = node;
char ch = word[0];
if (ch == '.'){
for (int i = 0; i < 26; i++){
if (level->next[i] != NULL){
if (search(word.substr(1), level->next[i]) == true){
return true;
}
}
}
return false;
}
else{
int i = word[0] - 'a';
if (level->next[i] == NULL){
return false;
}
else{
return search(word.substr(1), level->next[i]);
}
}
}

private:
TrieNode* root;
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: