208. Implement Trie (Prefix Tree)

Posted ruisha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了208. Implement Trie (Prefix Tree)相关的知识,希望对你有一定的参考价值。

Implement a trie with insertsearch, 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

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

 

Trie的基本实现:

 1 struct TrieNode{
 2     TrieNode* children[26];
 3     bool isWord;
 4     TrieNode(){
 5         for(int i=0;i<26;i++){
 6             children[i]=NULL;
 7         }
 8     }
 9     ~TrieNode(){
10         for(int i=0;i<26;i++){
11             delete children[i];
12         }
13     }
14 };
15 class Trie {
16 private:
17     TrieNode* root;
18 public:
19     /** Initialize your data structure here. */
20     Trie() {
21         root = new TrieNode();
22     }
23     
24     /** Inserts a word into the trie. */
25     void insert(string word) {
26         TrieNode* curr = root;
27         for(auto c: word){
28             if(curr->children[c-a]==NULL){
29                 curr->children[c-a] = new TrieNode();
30             }
31             curr = curr->children[c-a];
32         }
33         curr->isWord = true;
34     }
35     
36     /** Returns if the word is in the trie. */
37     bool search(string word) {
38         TrieNode* curr = root;
39         for(auto c: word){
40             if(curr->children[c-a]==NULL){
41                 return false;  
42             }
43             curr = curr->children[c-a];
44         }
45         
46         return curr->isWord;
47     }
48     
49     /** Returns if there is any word in the trie that starts with the given prefix. */
50     bool startsWith(string prefix) {
51         TrieNode* curr = root;
52         for(auto c: prefix){
53             if(curr->children[c-a]==NULL){
54                 return false;
55             }
56             curr=curr->children[c-a];
57         }
58         
59         return true;
60     }
61 };
62 
63 /**
64  * Your Trie object will be instantiated and called as such:
65  * Trie obj = new Trie();
66  * obj.insert(word);
67  * bool param_2 = obj.search(word);
68  * bool param_3 = obj.startsWith(prefix);
69  */

 

以上是关于208. Implement Trie (Prefix Tree)的主要内容,如果未能解决你的问题,请参考以下文章

208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

[LeetCode] 208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)