Leetcode 208: Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

 

 1 public class Trie {
 2  // prefix tree node
 3     public class TreeNode
 4     {
 5         public bool isWord;
 6         public TreeNode[] children;
 7         public char val;
 8         
 9         public TreeNode(char val, bool isWord)
10         {
11             this.val = val;
12             this.isWord = isWord;
13             this.children = new TreeNode[26];
14         }
15         
16         public void AddChild(char c)
17         {
18             int index = this.GetIndex(c);
19             
20             if (this.children[index] == null)
21             {
22                 this.children[index] = new TreeNode(c, false);
23             }
24         }
25         
26         public TreeNode GetChild(char c)
27         {
28             return this.children[this.GetIndex(c)];
29         }
30         
31         private int GetIndex(char c)
32         {
33             return (int)c - (int)'a';
34         }
35     }
36     
37     private TreeNode root = new TreeNode('*', false);
38     
39     /** Initialize your data structure here. */
40     public Trie() {
41         
42     }
43     
44     /** Inserts a word into the trie. */
45     public void Insert(string word) {
46         this.InsertWord(this.root, word, 0);
47     }
48     
49     private void InsertWord(TreeNode node, string s, int start)
50     {
51         if (start >= s.Length)
52         {
53             node.isWord = true;
54             return;
55         }
56         
57         char c = s[start];
58         
59         node.AddChild(c);
60         
61         InsertWord(node.GetChild(c), s, start + 1);
62     }
63     
64     /** Returns if the word is in the trie. */
65     public bool Search(string word) {
66         return this.DFS(this.root, word, 0, false);
67     }
68     
69     private bool DFS(TreeNode node, string s, int start, bool prefix)
70     {
71         if (start >= s.Length)
72         {
73             return prefix || node.isWord;
74         }
75         
76         char c = s[start];
77         
78         if (node.GetChild(c) == null) return false;
79         
80         return DFS(node.GetChild(c), s, start + 1, prefix);
81     }
82     
83     /** Returns if there is any word in the trie that starts with the given prefix. */
84     public bool StartsWith(string prefix) {
85         return this.DFS(this.root, prefix, 0, true);
86     }
87 }
88 
89 
90 /**
91  * Your Trie object will be instantiated and called as such:
92  * Trie obj = new Trie();
93  * obj.Insert(word);
94  * bool param_2 = obj.Search(word);
95  * bool param_3 = obj.StartsWith(prefix);
96  */

 

posted @ 2017-11-29 09:42  逸朵  阅读(133)  评论(0)    收藏  举报