您的位置:首页 > 其它

[LeetCode] Add and Search Word - Data structure design

2015-05-16 15:42 561 查看
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
.

字典树,注意匹配 '.' 的时候要对所有的子树进行匹配,这时就得用DFS了。

class WordDictionary {
private:
struct trinode {
trinode *ch[26];
bool iskey;
trinode(): iskey(false) {
for (auto &a : ch) a = NULL;
}
};

trinode *root;

void _addWord(string s) {
trinode *p = root;
for (auto &a : s) {
int idx = a - 'a';
if (p->ch[idx] == NULL) p->ch[idx] = new trinode();
p = p->ch[idx];
}
p->iskey = true;
}

bool _search(trinode *root, string s, int pos) {
if (pos == s.length()) return root->iskey;
if (s[pos] == '.') {
for (auto &p : root->ch) {
if (p != NULL && _search(p, s, pos + 1)) return true;
}
return false;
} else {
int idx = s[pos] - 'a';
return (root->ch[idx] && _search(root->ch[idx], s, pos + 1));
}
}

public:
WordDictionary() {
root = new trinode();
}
// Adds a word into the data structure.
void addWord(string word) {
_addWord(word);
}

// 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);
}
};

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


搜索的时候可以只有遇到 '.' 的时候才递归,否则就迭代。可以提高一点点效率。

bool _search(trinode *root, string s, int pos) {
if (pos == s.length()) return root->iskey;
trinode *p = root;
for (; pos < s.length(); ++pos) {
if (s[pos] != '.') {
int idx = s[pos] - 'a';
if (p->ch[idx] == NULL) return false;
p = p->ch[idx];
} else {
for (int idx = 0; idx < 26; ++idx) {
if (p->ch[idx] && __search(p->ch[idx], s, pos + 1)) return true;
}
return false;
}
}
return p->iskey;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: