标签:
Implement a trie with insert, search,
and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
在Trie树中主要有3个操作,插入、查找和删除。一般情况下Trie树中很少存在删除单独某个结点的情况,因此只考虑删除整棵树。
1、插入
假设存在字符串str,Trie树的根结点为root。i=0,p=root。
1)取str[i],判断p->next[str[i]-97]是否为空,若为空,则建立结点temp,并将p->next[str[i]-97]指向temp,然后p指向temp;
若不为空,则p=p->next[str[i]-97];
2)i++,继续取str[i],循环1)中的操作,直到遇到结束符‘\0‘,此时将当前结点p中的 exist置为true。
2、查找
假设要查找的字符串为str,Trie树的根结点为root,i=0,p=root
1)取str[i],判断判断p->next[str[i]-97]是否为空,若为空,则返回false;若不为空,则p=p->next[str[i]-97],继续取字符。
2)重复1)中的操作直到遇到结束符‘\0‘,若当前结点p不为空并且 exist 为true,则返回true,否则返回false。
3、删除
删除可以以递归的形式进行删除。
class TrieNode {
public:
// Initialize your data structure here.
TrieNode *next[26]; //指向子树的指针
bool exist;
TrieNode() {
memset(next, 0, 26*sizeof(TrieNode*));
exist = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode* p = root;
int len = word.size();
int i =0;
while(i < len)
{
if(p->next[word[i]-'a']==NULL)
{
p->next[word[i]-'a'] = new TrieNode;
}
p = p->next[word[i]-'a'];
i++;
}
p->exist = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode* p = root;
int len = word.size();
int i = 0;
while(i < len)
{
p = p->next[word[i]-'a'];
if(p==NULL)
return false;
else
{
i++;
}
}
if(p->exist==true)
return true;
else
return false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* p = root;
int len = prefix.length();
int i = 0;
while(i < len)
{
p = p->next[prefix[i]-'a'];
if(p==NULL)
return false;
else
{
i++;
}
}
return true;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");208. Implement Trie (Prefix Tree)字典树
标签:
原文地址:http://blog.csdn.net/qq_27991659/article/details/51353000