您的位置:首页 > 其它

单词的添加与查找-LintCode

2017-10-20 18:41 357 查看
设计一个包含下面两个操作的数据结构: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


#ifndef C473_H
#define C473_H
#include<iostream>
#include<string>
using namespace std;
class WordDictionaryNode{
public:
WordDictionaryNode *child[26];
bool isWord;
WordDictionaryNode()
{
this->isWord = false;
for (auto &c : child)
c = NULL;
}
};
class WordDictionary {
public:
/*
* @param word: Adds a word into the data structure.
* @return: nothing
*/
WordDictionary()
{
root = new WordDictionaryNode();
}
void addWord(string &word) {
// write your code here
WordDictionaryNode *p = root;
for (auto c : word)
{
int i = c - 'a';
if (!p->child[i])
p->child[i] = new WordDictionaryNode();
p = p->child[i];
}
p->isWord = true;
}

/*
* @param word: A word could contain the dot character '.' to represent any one letter.
* @return: if the word is in the data structure.
*/
bool search(string &word) {
// write your code here
return searchRecur(word, root,0);
}
bool searchRecur(string &word, WordDictionaryNode *p,int pos)
{
if (pos >= word.size())
return p->isWord;
if (word[pos] == '.')
{
for (auto c : p->child)
{
if (c&&searchRecur(word, c, pos + 1))
return true;
}
return false;
}
else
return p->child[word[pos] - 'a'] && searchRecur(word, p->child[word[pos] - 'a'], pos + 1);
}
private:
WordDictionaryNode *root;
};

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