File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TrieNode {
2
+ TrieNode [] children ;
3
+ boolean isEndOfWord ;
4
+
5
+ public TrieNode () {
6
+ children = new TrieNode [26 ];
7
+ isEndOfWord = false ;
8
+ }
9
+ }
10
+
11
+ class Trie {
12
+
13
+ private TrieNode root ;
14
+
15
+ public Trie () {
16
+ root = new TrieNode ();
17
+ }
18
+
19
+ // TC: O(n)
20
+ // SC: O(n * m)
21
+ // -> word length * new TrieNode spaces
22
+ public void insert (String word ) {
23
+ TrieNode node = root ;
24
+ for (char c : word .toCharArray ()) {
25
+ int idx = c - 'a' ;
26
+ if (node .children [idx ] == null ) {
27
+ node .children [idx ] = new TrieNode ();
28
+ }
29
+ node = node .children [idx ];
30
+ }
31
+ node .isEndOfWord = true ;
32
+ }
33
+
34
+ // TC: O(n)
35
+ // SC: O(1)
36
+ public boolean search (String word ) {
37
+ TrieNode node = searchPrefix (word );
38
+ return node != null && node .isEndOfWord ;
39
+ }
40
+
41
+ // TC: O(n)
42
+ // SC: O(1)
43
+ private TrieNode searchPrefix (String word ) {
44
+ TrieNode node = root ;
45
+ for (char c : word .toCharArray ()) {
46
+ int idx = c - 'a' ;
47
+ if (node .children [idx ] == null ) return null ;
48
+ node = node .children [idx ];
49
+ }
50
+ return node ;
51
+ }
52
+
53
+ public boolean startsWith (String prefix ) {
54
+ return searchPrefix (prefix ) != null ;
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments