题目来源:Add and Search Word - Data structure design
写过Implement Trie (Prefix Tree) 就不难想到这题又是典型的Trie(前缀树或者叫字典树),这个WordDictionary就是建立在Trie之上的,addWord和search就是Trie的插入和查找,唯一不同之处是search引入了正则符号(.)表示”任意单个字母“。需要注意的是:
1.考虑用递归处理正则符号(.);
2.注意插入和查询时的结束逻辑。比如插入"aaa"后,查询"a"和"aa"应该是失败的。
注意以上几点就不难写出以下代码:
struct TrieNode{
std::unordered_map<char,TrieNode *> children;
};
class WordDictionary {
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode *pnode = root;
for(int i=0; i<word.size(); i++) {
if(pnode->children.find(word[i]) == pnode->children.end()) {
pnode->children[word[i]] = new TrieNode();
}
pnode = pnode->children[word[i]];
}
//'@' represents the ending flag.
if(pnode->children.find('@') == pnode->children.end())
pnode->children['@'] = NULL;
}
bool search(string word) {
if(word.size() == 0)
return false;
return search_recursive(root,word);
}
private:
TrieNode *root;
bool search_recursive(TrieNode *pn, string str) {
if(str.size() == 0) {
if(pn->children.find('@') != pn->children.end())
return true;
else
return false;
}
if(str[0] == '.') {
for(unordered_map<char,TrieNode *>::iterator it=pn->children.begin(); it!=pn->children.end(); it++)
if(it->first != '@' && search_recursive(it->second,str.substr(1)))
return true;
} else if(pn->children.find(str[0]) != pn->children.end()) {
return search_recursive(pn->children[str[0]],str.substr(1));
}
return false;
}
};
以上代码是边写边改的结果,所以结束符草草完成逻辑就完事了,耗时大约在300~400ms。实际上,结束符本来就是Trie的一部分,不妨将其整合到data structrue里:
struct TrieNode{
TrieNode() {ending = false;}
bool ending;
std::unordered_map<char,TrieNode *> children;
};
修改后,运行时间大约为200ms。如果还要继续优化,就需要对递归进行改写了,毕竟递归层数多了还是很影响效率的,有空再来优化试试。另外在discuss中,有一个答案直接使用内置数组来存储children,试了一下能在100ms左右运行完毕,有时候太依赖STL也是不好的。