File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+
3
+ class Node {
4
+ boolean isEnd ;
5
+ Node [] childs = new Node [26 ];
6
+ Node () {}
7
+ }
8
+
9
+ private Node root ;
10
+
11
+ public Trie () {
12
+ this .root = new Node ();
13
+ }
14
+
15
+ // O(m) when m is the length of word
16
+ public void insert (String word ) {
17
+ Node curN = this .root ;
18
+ for (char c : word .toCharArray ()) {
19
+ if (curN .childs [c -'a' ] == null ) {
20
+ curN .childs [c -'a' ] = new Node ();
21
+ }
22
+ curN = curN .childs [c -'a' ];
23
+ }
24
+ //end
25
+ curN .isEnd = true ;
26
+ }
27
+ // O(k) when k is the length of searching word
28
+ public boolean search (String word ) {
29
+ Node curN = this .root ;
30
+ for (char c : word .toCharArray ()) {
31
+ if (curN .childs [c -'a' ] == null ) return false ;
32
+ curN = curN .childs [c -'a' ];
33
+ }
34
+ return curN .isEnd ;
35
+ }
36
+
37
+ // O(k) when k is the length of prefix
38
+ public boolean startsWith (String prefix ) {
39
+ Node curN = this .root ;
40
+ for (char c : prefix .toCharArray ()) {
41
+ if (curN .childs [c -'a' ] == null ) return false ;
42
+ curN = curN .childs [c -'a' ];
43
+ }
44
+ return true ;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Your Trie object will be instantiated and called as such:
50
+ * Trie obj = new Trie();
51
+ * obj.insert(word);
52
+ * boolean param_2 = obj.search(word);
53
+ * boolean param_3 = obj.startsWith(prefix);
54
+ */
You can’t perform that action at this time.
0 commit comments