Problem
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
Solution
用 Trie实现就好了。
但是有一点很容易出错,什么时候才能算是找到?first thought是走到叶子节点才行,其实不然,比如
add "ab" , add "a" , 然后 search "a", 这样因为还没有到达叶子节点b 就返回错;
修正:
每个TreeNode都加一个属性是否是单词的最后一个字符 (isLast)
struct TreeNode2 {
TreeNode2(char c) : letter(c), isLast(false) {}
char letter;
vector<TreeNode2*> neighbs;
bool isLast;
};
class WordDictionary {
TreeNode2* root;
void addHelper(TreeNode2* root, int idx, const string& word){
if(idx == word.size()){
return;
}
for( auto neighb : root->neighbs) {
if( word[idx] == neighb->letter){
return addHelper( neighb, idx + 1, word);
}
}
TreeNode2* newNeighb = new TreeNode2(word[idx]);
if( idx == word.size() -1) { newNeighb->isLast = true;}
(root->neighbs).push_back(newNeighb);
return addHelper( newNeighb, idx+1, word);
}
bool searchHelper(TreeNode2* root, int idx, const string& word){
if(idx == word.size() && root->isLast) return true;
if(idx == word.size()) return false;
if( word[idx] == '.' ){
for( auto neighb : root->neighbs ) {
if( searchHelper( neighb, idx + 1, word)) return true;
}
}
for( auto neighb : root->neighbs ){
if( neighb->letter == word[idx]) {
return searchHelper( neighb, idx + 1, word);
}
}
return false;
}
public:
WordDictionary():root(new TreeNode2('0')){}
// Adds a word into the data structure.
void addWord(string word) {
addHelper(root, 0, 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 searchHelper( root, 0, word);
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
本文介绍了一种使用Trie数据结构实现单词字典的方法,支持两种操作:添加单词(addWord)和根据正则表达式进行搜索(search),其中正则表达式可以包含任意字母或'.'符号,'.'可以匹配任何一个字母。
460

被折叠的 条评论
为什么被折叠?



