forked from ByteByteGoHq/coding-interview-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesignATrie.java
More file actions
60 lines (54 loc) · 1.72 KB
/
DesignATrie.java
File metadata and controls
60 lines (54 loc) · 1.72 KB
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
import java.util.HashMap;
import java.util.Map;
class TrieNode {
Map<Character, TrieNode> children;
boolean isWord;
public TrieNode() {
this.children = new HashMap<>();
this.isWord = false;
}
}
public class DesignATrie {
TrieNode root;
public DesignATrie() {
this.root = new TrieNode();
}
public void insert(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
// For each character in the word, if it's not a child of
// the current node, create a new TrieNode for that
// character.
node.children.putIfAbsent(c, new TrieNode());
node = node.children.get(c);
}
// Mark the last node as the end of a word.
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
// For each character in the word, if it's not a child of
// the current node, the word doesn't exist in the Trie.
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);
}
// Return whether the current node is marked as the end of the
// word.
return node.isWord;
}
public boolean hasPrefix(String prefix) {
TrieNode node = this.root;
for (char c : prefix.toCharArray()) {
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);
}
// Once we've traversed the nodes corresponding to each
// character in the prefix, return True.
return true;
}
}