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.
基本思路:
和上面问题差不多。需要实现一个字典树。
不同的是,支持‘.‘这个符号的查找时,需要用到递归。进行多路径偿试。
class WordDictionary {
public:
WordDictionary() : root(new TrieNode()) {}
// Adds a word into the data structure.
void addWord(string word) {
TrieNode *runner = root;
for (auto ch: word) {
runner = runner->get(ch, true);
}
runner->isword = true;
}
// 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(word, 0, root);
}
private:
class TrieNode {
public:
TrieNode() : branch(26), isword(false) {}
TrieNode *get(char ch, bool create = false) {
const int index = ch - 'a';
if (!branch[index] && create)
branch[index] = new TrieNode();
return branch[index];
}
vector<TrieNode*> branch;
bool isword;
};
bool search(const string &word, int index, TrieNode *node) {
if (!node)
return false;
if (index == word.size())
return node->isword;
if (word[index] != '.')
return search(word, index+1, node->get(word[index]));
for (char ch='a'; ch<='z'; ch++) {
if (search(word, index+1, node->get(ch)))
return true;
}
return false;
}
TrieNode *root;
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");版权声明:本文为博主原创文章,未经博主允许不得转载。
Add and Search Word - Data structure design -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/47374491