-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.java
48 lines (42 loc) · 949 Bytes
/
14.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
class TrieNode {
private HashMap < Character,
TrieNode > children = new HashMap < >();
public boolean isEnd = false; // "public" for simplicity
public void putChildIfAbsent(char ch) {
children.putIfAbsent(ch, new TrieNode());
}
public TrieNode getChild(char ch) {
return children.get(ch);
}
}
class Trie {
TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode curr = root;
for (char ch: word.toCharArray()) {
curr.putChildIfAbsent(ch);
curr = curr.getChild(ch);
}
curr.isEnd = true;
}
public boolean search(String word) {
TrieNode curr = root;
for (char ch: word.toCharArray()) {
curr = curr.getChild(ch);
if (curr == null) {
return false;
}
}
return curr.isEnd;
}
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (char ch: prefix.toCharArray()) {
curr = curr.getChild(ch);
if (curr == null) {
return false;
}
}
return true;
}
}