-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathImplementTrie.java
More file actions
66 lines (46 loc) · 1.24 KB
/
Copy pathImplementTrie.java
File metadata and controls
66 lines (46 loc) · 1.24 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
class Node{
private boolean isWord;
private Map<Character, Node> children = new HashMap<>();
public void setEndOfWord(boolean isWord) {
this.isWord = isWord;
}
public boolean isEndOfWord() {
return isWord;
}
public Map<Character, Node> getChildren() {
return children;
}
}
class Trie {
private Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
Node current = root;
for (char c: word.toCharArray()) {
current = current.getChildren().computeIfAbsent(c, x -> new Node());
}
current.setEndOfWord(true);
}
public boolean search(String word) {
Node current = root;
for (char c : word.toCharArray() ) {
current = current.getChildren().get(c);
if (current == null){
return false;
}
}
return current.isEndOfWord();
}
public boolean startsWith(String prefix) {
Node current = root;
for (char c : prefix.toCharArray() ) {
current = current.getChildren().get(c);
if (current == null){
return false;
}
}
return true;
}
}