1
+ // Time Complexity: O(n), n: word.length()
2
+ // Space Complexity: O(n), n: word.length()
3
+ class Trie {
4
+ private static class TrieNode {
5
+ HashMap <Character , TrieNode > trieNodeMap ;
6
+ boolean isEnd ;
7
+
8
+ private TrieNode () {
9
+ this .trieNodeMap = new HashMap <>();
10
+ this .isEnd = false ;
11
+ }
12
+ }
13
+
14
+ private TrieNode rootNode ;
15
+
16
+ public Trie () {
17
+ this .rootNode = new TrieNode ();
18
+ }
19
+
20
+ public void insert (String word ) {
21
+ TrieNode currentNode = this .rootNode ;
22
+
23
+ for (char ch : word .toCharArray ()) {
24
+ if (!currentNode .trieNodeMap .containsKey (ch )) {
25
+ currentNode .trieNodeMap .put (ch , new TrieNode ());
26
+ }
27
+ currentNode = currentNode .trieNodeMap .get (ch );
28
+ }
29
+ currentNode .isEnd = true ;
30
+ }
31
+
32
+ public boolean search (String word ) {
33
+ TrieNode currentNode = this .rootNode ;
34
+
35
+ for (char ch : word .toCharArray ()) {
36
+ if (!currentNode .trieNodeMap .containsKey (ch )) {
37
+ return false ;
38
+ }
39
+ currentNode = currentNode .trieNodeMap .get (ch );
40
+ }
41
+
42
+ return currentNode .isEnd ;
43
+ }
44
+
45
+ public boolean startsWith (String prefix ) {
46
+ TrieNode currentNode = this .rootNode ;
47
+
48
+ for (char ch : prefix .toCharArray ()) {
49
+ if (!currentNode .trieNodeMap .containsKey (ch )) {
50
+ return false ;
51
+ }
52
+ currentNode = currentNode .trieNodeMap .get (ch );
53
+ }
54
+
55
+ return true ;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Your Trie object will be instantiated and called as such:
61
+ * Trie obj = new Trie();
62
+ * obj.insert(word);
63
+ * boolean param_2 = obj.search(word);
64
+ * boolean param_3 = obj.startsWith(prefix);
65
+ */
0 commit comments