Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
操作:
trie.insert(“apple”);
trie.search(“apple”); // returns true
trie.search(“app”); // returns false
trie.startsWith(“app”); // returns true
trie.insert(“app”);
trie.search(“app”); // returns true
思路:
完成两件事:1,解决查找完全单词的功能;2,查找部分(即前缀单词)的功能。
方法:使用一个树,每个节点有26个数组格,维护一个根节点当来了新的单词
插入: 从根节点开始,第一个单词对应的数组项如果为空,就新建一个节点然后从这个节点继续遍历单词。并且最后将flag标准设真
查找完整单词:从根节点开始,如果对应的项非空并且单词的标志为真**(说明到这个点了刚好是单词)**。继续往下
查找前缀:和完整查找类似,不过不需要判断标志,因为仅仅需要前缀。
构造时,析构时:递归释放空间。
代码:
class TrieNode{
public:
TrieNode(bool b=false ){
is_word=b;
memset(next, 0,sizeof(next));
}
TrieNode *next[26];
bool is_word;
};
class Trie {
private:
TrieNode* root;
public:
/** Initialize your data structure here. */
Trie() {
root= new TrieNode;
}
~Trie( ){
clear(root); //更需要清除细节的部分
}
/** Inserts a word into the trie. */
void insert(string word) {
auto tmp=root;
for(auto c:word){
if(tmp->next[c-'a'] == nullptr)
tmp->next[c-'a'] =new TrieNode;
tmp=tmp->next[c-'a'];
}
tmp->is_word=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
auto tmp=find_string(word);
if(tmp !=nullptr && (tmp->is_word))
return true;
else
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
//找前缀和上一个有点不同
auto tmp=find_string(prefix);
if(tmp != nullptr)
return true;
else
return false;
}
private:
TrieNode* find_string(std::string word){
auto tmp=root;
for(auto c:word)
{
if(tmp->next[c-'a'] !=nullptr )
tmp=tmp->next[c-'a'];
else{
tmp=nullptr;
break;
}
}
return tmp;
}
void clear(TrieNode* root){
for(int i=0;i<26;++i) //递归释放
{
if(root->next[i] != nullptr)
clear(root->next[i]);
}
delete root;
}
};
/**
* 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);
*/