Repository navigation
Expand file tree
/
Copy pathTrie.java
More file actions
78 lines (52 loc) · 1.6 KB
/
Copy pathTrie.java
File metadata and controls
78 lines (52 loc) · 1.6 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package modern.challenge;
import java.util.function.Function;
class Trie {
private final Node root;
public Trie() {
root = new Node();
}
public boolean contains(String word) {
Node node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
node = node.getChildren().get(ch);
if (node == null) {
return false;
}
}
return node.isWord();
}
@SuppressWarnings("unchecked")
public void insert(String word) {
Node node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
Function function = k -> new Node();
node = node.getChildren().computeIfAbsent(ch, function);
}
node.setWord(true);
}
public boolean delete(String word) {
return delete(root, word, 0);
}
private boolean delete(Node node, String word, int position) {
if (word.length() == position) {
if (!node.isWord()) {
return false;
}
node.setWord(false);
return node.getChildren().isEmpty();
}
char ch = word.charAt(position);
Node children = node.getChildren().get(ch);
if (children == null) {
return false;
}
boolean deleteChildren = delete(children, word, position + 1);
if (deleteChildren && !children.isWord()) {
node.getChildren().remove(ch);
return node.getChildren().isEmpty();
}
return false;
}
}