-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
55 lines (45 loc) · 1.33 KB
/
Solution.java
File metadata and controls
55 lines (45 loc) · 1.33 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
package org.example.problems.implement_trie;
import org.example.problems.SolutionInterface;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "Implement Trie";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/implement-trie-prefix-tree/";
}
private final Node root = new Node();
public void insert(String word) {
Node node = root;
for (char c: word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new Node();
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
Node node = getLastNode(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
return getLastNode(prefix) != null;
}
private Node getLastNode(String word) {
Node node = root;
for (char c: word.toCharArray()) {
node = node.children[c - 'a'];
if (node == null) {
return null;
}
}
return node;
}
private static class Node {
public boolean isEnd = false;
public Node[] children = new Node[26];
}
}