forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
79 lines (66 loc) · 2.05 KB
/
Trie.java
File metadata and controls
79 lines (66 loc) · 2.05 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
79
import java.util.*;
public class Trie {
private TrieNode root;
public Trie() {
this.root = new TrieNode();
}
/**
* Insert a word into the trie.
*
* @param word The word to insert.
*/
public void insert(String word) {
Map<Character, TrieNode> children = root.children;
for (int i = 0; i < word.length(); i++) {
TrieNode node;
char c = word.charAt(i);
if (children.containsKey(c)) {
node = children.get(c);
} else {
/**
* At this point, we know if we couldn't find word.charAt(i) in our trie,
* the word doesn't exist. Create a new TrieNode and populate it's child.
*/
node = new TrieNode();
children.put(c, node);
}
children = node.children;
}
// Once we've reached the end of the word, mark the node as a leaf.
node.endOfWord = true;
}
/**
* Lookup a word in the trie.
*
* @param word The word to lookup.
* @return True if the trie structure contains the word.
*/
public boolean lookup(String word) {
Map<Character, TrieNode> children = root.children;
/**
* For each letter in the word, traverse to the deepest child found.
*/
for (int i = 0; i < word.length(); i++) {
TrieNode node;
char c = word.charAt(i);
if (children.containsKey(c)) {
node = children.get(c);
children = node.children;
} else {
/* If at any point a character in the word isn't found, return false as the word doesn't exist. */
return false;
}
}
return true;
}
/**
* Each node contains a hashmap of children nodes.
*/
static class TrieNode {
Map<Character, TrieNode> children;
boolean endOfWord;
public TrieNode() {
this.children = new HashMap<>();
}
}
}