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.

 

实现字典树

 

C++:

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

 

posted @ 2019-01-17 15:35  __Meng  阅读(136)  评论(0编辑  收藏  举报