单词的添加与查找
设计一个包含下面两个操作的数据结构:addWord(word)
, search(word)
addWord(word)
会在数据结构中添加一个单词。而search(word)
则支持普通的单词查询或是只包含.
和a-z
的简易正则表达式的查询。
一个 .
可以代表一个任何的字母。
注意事项
你可以假设所有的单词都只包含小写字母 a-z。
样例
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") // return false
search("bad") // return true
search(".ad") // return true
search("b..") // return true
AC代码如下:
struct trieNode {
trieNode() : terminableSize(0) {
for (int i = 0; i < 26; ++i) {
children[i] = NULL;
}
}
~trieNode() {
for (int i = 0; i < 26; ++i) {
if (children[i]) {
delete children[i];
children[i] = NULL;
}
}
}
int terminableSize;
trieNode *children[26];
};
class WordDictionary {
public:
WordDictionary() : root(new trieNode) {}
size_t Index(char c) {
return static_cast<size_t>(c % 26);
}
// Adds a word into the data structure.
void addWord(string word) {
// Write your code here
trieNode *cur = root;
for (size_t i = 0; i < word.size(); ++i) {
size_t idx = Index(word[i]);
if (!cur->children[idx]) {
cur->children[idx] = new trieNode;
}
cur = cur->children[idx];
}
++cur->terminableSize;
}
// 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_dfs(word, root);
}
bool search_dfs(string word, trieNode *cur) {
if (word.size() == 0 && cur->terminableSize > 0)
return true;
for (size_t i = 0; i < word.size(); ++i) {
if (word[i] == '.') {
for (size_t j = 0; j < 26; ++j) {
if (cur->children[j] && search_dfs(word.substr(i + 1), cur->children[j]))
return true;
}
return false;
}
else {
size_t idx = Index(word[i]);
if (!cur->children[idx])
return false;
cur = cur->children[idx];
}
}
if (cur->terminableSize > 0)
return true;
return false;
}
private:
trieNode *root;
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");