您的位置:首页 > 其它

Leetcode 211. Add and Search Word - Data structure design

2018-02-28 15:19 603 查看
原题:
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
.click to show hint.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.

解决方法:
看到了吧,Trie又来了,我的代码里写成TierNode,为什么,故意的,看看你们是不是抄成一样了。

代码:
class WordDictionary {
struct TierNode{
TierNode* next[26] = {0};
bool isWord = false;
};
TierNode root;

bool search(TierNode* node, string& word, int start){
for(int i = start; i < word.size(); i++){
if (!node)
break;
if (word[i] == '.'){
for(int j = 0; j < 26;j++){
if (!node->next[j])
continue;

if (search(node->next[j], word, i+1))
return true;
}
return false;
}else{
node = node->next[word[i] - 'a'];
}

}
return node && node->isWord;
}
public:
/** Initialize your data structure here. */
WordDictionary() {

}

/** Adds a word into the data structure. */
void addWord(string word) {
TierNode* node =&root;
for(int i = 0; i < word.size(); i++){
int index = word[i] - 'a';
if (!node->next[index])
node->next[index] = new TierNode;

node =node->next[index];
}
node->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(&root, word, 0);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode cplusplus