您的位置:首页 > 其它

leetcode 211. Add and Search Word - Data structure design

2017-11-24 09:31 513 查看
211. Add and Search Word - Data structure design

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 
.
.
.
 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 TNode
{
public:
char key;
bool isword;
TNode *child[26];

TNode()
{
key=0;
isword=false;
memset(child, 0, sizeof(TNode *) * 26);
}

TNode(char c)
{
key=c;
isword=false;
memset(child, 0, sizeof(TNode *) * 26);
}

};

class WordDictionary {
private:
TNode *root;

public:
/** Initialize your data structure here. */
WordDictionary()
{
root = new TNode();
}

/** Adds a word into the data structure. */
void addWord(string word)
{
TNode *p = root;
for (int i = 0; i < word.size(); i++)
{
if ( p->child[word[i]-'a'] == 0 )
{
TNode *pNode = new TNode(word[i]);
p->child[word[i]-'a'] = pNode;
}
p = p->child[word[i]-'a'];
}
p->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(root, word, 0);
}

bool search(TNode * pNode, string word, int pos)
{
TNode *p = pNode;
for(int i = pos; i < word.size(); i++)
{
if (p && word[i] == '.')
{
for(int j = 0; j < 26; j++)
{
if (search(p->child[j], word, i+1))
return true;
}
return false;
}
else if (p && word[i] != '.')
{
p = p->child[word[i]-'a'];
}
else
break;
}
return (p && p->isword);
}
};

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