-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTrie.java
More file actions
81 lines (60 loc) · 1.77 KB
/
Trie.java
File metadata and controls
81 lines (60 loc) · 1.77 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
80
81
import java.util.Map;
import java.util.HashMap;
class TrieNode{
boolean isWord;
char key;
Map<Character, TrieNode> children = new HashMap<>();
}
class Trie{
private static TrieNode root;
public Trie() {
root = new TrieNode();
}
//add each letter of the word to the trie
public static void addWord(String word) {
Map<Character, TrieNode> children = root.children;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
TrieNode current;
if (children.containsKey(c)) {
current = children.get(c);
} else{
current = new TrieNode();
children.put(c, current);
}
children = current.children;
if (i == word.length() - 1) {
//set node as last node
current.isWord = true;
}
}
}
public boolean search(String word) {
TrieNode current = searchNode(word);
if (current != null && current.isWord) {
return true;
} else {
return false;
}
}
public TrieNode searchNode(String word) {
Map<Character, TrieNode> children = root.children;
TrieNode current = null;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (children.containsKey(c)) {
current = children.get(c);
children = current.children;
} else {
return null;
}
}
return current;
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.addWord("amy");
trie.addWord("ann");
System.out.println(trie.search("ann"));
}
}