|
1 |
| -public class Trie { |
| 1 | +import java.util.Optional; |
2 | 2 |
|
3 |
| - private final TrieNode root; |
| 3 | + |
| 4 | +class Trie { |
| 5 | + |
| 6 | + private final Node root; |
4 | 7 |
|
5 | 8 | public Trie() {
|
6 |
| - this.root = new TrieNode(); |
| 9 | + root = new Node(); |
7 | 10 | }
|
8 | 11 |
|
9 | 12 | public void insert(String word) {
|
10 |
| - TrieNode curr = root; |
| 13 | + Node curr = root; |
11 | 14 | for (char c : word.toCharArray()) {
|
12 | 15 | if (!curr.children.containsKey(c)) {
|
13 |
| - curr.children.put(c, new TrieNode()); |
| 16 | + curr.children.put(c, new Node()); |
14 | 17 | }
|
15 | 18 | curr = curr.children.get(c);
|
16 | 19 | curr.startingWordCount++;
|
17 | 20 | }
|
18 |
| - curr.completeWordCount++; |
| 21 | + curr.endingWordCount++; |
19 | 22 | }
|
20 | 23 |
|
21 | 24 | public int countWordsEqualTo(String word) {
|
22 |
| - TrieNode endNode = searchWord(word); |
23 |
| - return endNode == null ? 0 : endNode.completeWordCount; |
| 25 | + Optional<Node> curr = search(word); |
| 26 | + return curr.map(node -> node.endingWordCount).orElse(0); |
24 | 27 | }
|
25 | 28 |
|
26 | 29 | public int countWordsStartingWith(String prefix) {
|
27 |
| - TrieNode endNode = searchWord(prefix); |
28 |
| - return endNode == null ? 0 : endNode.startingWordCount; |
| 30 | + Optional<Node> curr = search(prefix); |
| 31 | + return curr.map(node -> node.startingWordCount).orElse(0); |
29 | 32 | }
|
30 | 33 |
|
31 | 34 | public void erase(String word) {
|
32 |
| - TrieNode curr = root; |
| 35 | + Node curr = root; |
33 | 36 | for (char c : word.toCharArray()) {
|
34 | 37 | curr = curr.children.get(c);
|
35 | 38 | curr.startingWordCount--;
|
36 | 39 | }
|
37 |
| - curr.completeWordCount--; |
| 40 | + curr.endingWordCount--; |
38 | 41 | }
|
39 | 42 |
|
40 |
| - private TrieNode searchWord(String word) { |
41 |
| - TrieNode curr = root; |
| 43 | + private Optional<Node> search(String word) { |
| 44 | + Node curr = root; |
42 | 45 | for (char c : word.toCharArray()) {
|
43 | 46 | if (!curr.children.containsKey(c)) {
|
44 |
| - return null; |
| 47 | + return Optional.empty(); |
45 | 48 | }
|
46 | 49 | curr = curr.children.get(c);
|
47 | 50 | }
|
48 |
| - return curr; |
| 51 | + return Optional.of(curr); |
49 | 52 | }
|
50 | 53 |
|
51 |
| - private static class TrieNode { |
52 |
| - Map<Character, TrieNode> children; |
53 |
| - int completeWordCount; |
54 |
| - int startingWordCount; |
| 54 | + private static class Node { |
55 | 55 |
|
56 |
| - public TrieNode() { |
57 |
| - this.children = new HashMap<>(); |
58 |
| - this.completeWordCount = 0; |
| 56 | + private int startingWordCount; |
| 57 | + private int endingWordCount; |
| 58 | + |
| 59 | + private final Map<Character, Node> children; |
| 60 | + |
| 61 | + public Node() { |
59 | 62 | this.startingWordCount = 0;
|
| 63 | + this.endingWordCount = 0; |
| 64 | + this.children = new HashMap<>(); |
60 | 65 | }
|
61 | 66 | }
|
62 | 67 | }
|
|
0 commit comments