您的位置:首页 > 其它

Leetcode题解 - 208. Implement Trie (Prefix Tree)

2017-03-31 14:32 375 查看
Implement a trie with insert, search, and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.

戳我

Trie即字典树或者前缀树,

如给出字符串”abc”,”ab”,”bd”,”dda”,根据该字符串序列构建一棵Trie树。则构建的树如下:



为了描述这个数据结构,先建立TrieNode这个类,即字典树的节点,每个结点包括26个孩子结点,因为总共有26个英文字母(假设单词都是小写字母组成)。

插入方法就是对于某个字符串,将其插入到一颗字典树的具体操作应该是从root节点开始,逐个查找对应字母的节点是否存在,如果不存在则创建对应的字典树节点,最后将isword即对应是否构成一个完整的词语。

对于search和startWith方法,可以先抽象出一个find方法,返回最后一个字母所在的节点,之后对于search方法就是判断返回的节点是否为空(单词不存在)以及返回的节点是否构成完整的单词,而startWith方法就是只判断是否为空就行了。

class TrieNode{
public:
TrieNode *next[26];//指向各个子树的指针
TrieNode(bool b=false){
memset(next,0,sizeof(next));
isword=b;//是否构成完整的单词
}
bool isword;

};

class Trie {
TrieNode *root;
TrieNode* find(string word){
TrieNode* p=root;
for(int i=0;i<word.size()&&p!=NULL;i++){
p=p->next[word[i]-'a'];
}
return p;

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

/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p=root;
for( int i=0;i<word.size();i++){
if(p->next[word[i]-'a']==NULL)
p->next[word[i]-'a']=new TrieNode();
p=p->next[word[i]-'a'];
}
p->isword=true;
}

/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p=find(word);
return p!=NULL && p->isword==true;
}

/** Returns if
4000
there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return find(prefix)!=NULL;
}
};

/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* bool param_2 = obj.search(word);
* bool param_3 = obj.startsWith(prefix);
*/


ref:

http://blog.csdn.net/hackbuteer1/article/details/7964147
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: