-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathTrie.java
63 lines (54 loc) · 1.52 KB
/
Trie.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package java1.algorithms.tree;
import java.util.HashMap;
class Node {
HashMap<Character, Node> children = new HashMap<>();
boolean isEnd = false;
}
public class Trie {
Node root;
Trie(){
this.root = new Node();
}
//TC: O(n) SC: O(n)
public void insert(String word) {
Node curr = root;
for(char ch: word.toCharArray()) {
if(!curr.children.containsKey(ch)) {
curr.children.put(ch, new Node());
}
curr = curr.children.get(ch);
}
curr.isEnd = true;
}
//TC: O(n) SC: O(1)
public boolean search(String word) {
Node curr = root;
for(char ch: word.toCharArray()) {
if(!(curr.children.containsKey(ch))) {
return false;
}
curr = curr.children.get(ch);
}
return curr.isEnd;
}
//TC: O(n) SC: O(1)
public boolean startsWith(String prefix) {
Node curr = root;
for(char ch: prefix.toCharArray()) {
if(!(curr.children.containsKey(ch))) {
return false;
}
curr = curr.children.get(ch);
}
return true;
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple"));
System.out.println(trie.search("app"));
System.out.println(trie.startsWith("app"));
trie.insert("app");
System.out.println(trie.search("app"));
}
}