您的位置:首页 > 其它

Add and Search Word - Data structure design - LeetCode

2015-11-09 08:04 411 查看
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 DictNode
{
public:
DictNode *dict[27];
DictNode ()
{
for (int i = 0; i < 27; i++)
dict[i] = NULL;
}
};
class WordDictionary {
public:
WordDictionary()
{
root = new DictNode();
}
// Adds a word into the data structure.
void addWord(string word) {
DictNode *cur = root;
for (int i = 0, len = word.size(); i < len; i++)
{
int loc = (int)(word[i] - 'a');
if (cur->dict[loc] == NULL)
cur->dict[loc] = new DictNode();
cur = cur->dict[loc];
}
if (cur->dict[26] == NULL)
cur->dict[26] = new DictNode();
}
bool help(DictNode *cur, string word)
{
if (cur == NULL) return false;
if (word.size() == 0)
{
if (cur->dict[26] == NULL) return false;
return true;
}
if (word[0] != '.')
{
int loc = (int)(word[0] - 'a');
return help(cur->dict[loc], (word.size() > 1 ? word.substr(1) : ""));
}
else
{
for (int i = 0; i < 26; i++) if (cur->dict[i] != NULL)
{
if (help(cur->dict[i], (word.size() > 1 ? word.substr(1) : "")))
return true;
}
return false;
}
}

// 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 help(root, word);
}
private:
DictNode *root;
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: