leetcode Add and Search Word - Data structure design
题目
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.
题目来源:https://leetcode.com/problems/add-and-search-word-data-structure-design/
分析
关于字典树(trie tree)的概念和分析见:http://blog.csdn.net/u010902721/article/details/45749447
主要挑战性在于’.’的匹配。遇到一个’.’就得匹配当前next[]数组里面所有的有效分支。用个递归函数,递归匹配吧。
代码
class TrieNode{
public:
int flag;
TrieNode* next[26];
TrieNode(){
flag = 0;
for(int i = 0; i < 26; i++){
next[i] = NULL;
}
}
};
class WordDictionary {
private:
TrieNode *root;
public:
WordDictionary(){
root = new TrieNode();
}
// Adds a word into the data structure.
void addWord(string word) {
TrieNode* p = root;
int len = word.length();
if(len <= 0)
return;
for(int i = 0; i < len; i++){
int d = word.at(i) - 'a';
if((p->next)[d] == NULL){
p->next[d] = new TrieNode();
p->next[d]->flag = 0;
}
p = p->next[d];
}
p->flag = 1;
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool searchHelp(string word, struct TrieNode *root){
struct TrieNode *p = root;
int len = word.length();
if(len <= 0){
//为了匹配字符串中字符'.'是最后一个字符的情形。
if(p->flag == 1)
return true;
else
return false;
}
if(root == NULL)
return false;
for(int i = 0; i < len; i++){
if(word.at(i) == '.'){
bool result = false;
for(int j = 0; j < 26; j++){
if(p->next[j] != NULL){
result = result || searchHelp(word.substr(i+1), p->next[j]);
}
}
return result;
}
else
{
int d = word.at(i) - 'a';
if(p->next[d] == NULL)
return false;
p = p->next[d];
}
}
if(p->flag == 1)
return true;
else
return false;
}
bool search(string word) {
int len = word.length();
if(len <= 0)
return true;
return searchHelp(word, root);
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
还没有评论,来说两句吧...