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 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: