208. 实现 Trie (前缀树)

主要是记录一下这个数据结构。

 

 

 比如这个trie树,包含三个单词:sea,sells,she。

代码:

 1 class Trie {
 2     bool isWord;
 3     vector<Trie*> children;
 4 public:
 5     /** Initialize your data structure here. */
 6     Trie() {
 7         isWord=false;
 8         children.assign(26,nullptr);
 9     }
10     
11     /** Inserts a word into the trie. */
12     void insert(string word) {
13         if(word.empty()){return;}
14         auto cur=this;
15         for(int i=0;i<word.size();++i){
16             if(cur->children[word[i]-'a']==nullptr){
17                 cur->children[word[i]-'a']=new Trie();
18             }
19             cur=cur->children[word[i]-'a'];
20         }
21         cur->isWord=true;
22     }
23     
24     /** Returns if the word is in the trie. */
25     bool search(string word) {
26         auto cur=this;
27         for(int i=0;i<word.size();++i){
28             if(cur->children[word[i]-'a']==nullptr){
29                 return false;
30             }
31             cur=cur->children[word[i]-'a'];
32         }
33         return cur->isWord;
34     }
35     
36     /** Returns if there is any word in the trie that starts with the given prefix. */
37     bool startsWith(string prefix) {
38         auto cur=this;
39         for(int i=0;i<prefix.size();++i){
40             if(cur->children[prefix[i]-'a']==nullptr){
41                 return false;
42             }
43             cur=cur->children[prefix[i]-'a'];
44         }
45         return true;
46     }
47 };
48 
49 /**
50  * Your Trie object will be instantiated and called as such:
51  * Trie* obj = new Trie();
52  * obj->insert(word);
53  * bool param_2 = obj->search(word);
54  * bool param_3 = obj->startsWith(prefix);
55  */

 

posted @ 2020-02-17 22:50  NeoZy  阅读(165)  评论(0编辑  收藏  举报