Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit d72e675

Browse filesBrowse files
committed
PR-97: Added Trie implementation
1 parent 63305ce commit d72e675
Copy full SHA for d72e675

File tree

Expand file treeCollapse file tree

1 file changed

+79
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+79
-0
lines changed

‎Data Structures/Trie/Trie.java

Copy file name to clipboard
+79Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import java.util.*;
2+
3+
public class Trie {
4+
private TrieNode root;
5+
6+
public Trie() {
7+
this.root = new TrieNode();
8+
}
9+
10+
/**
11+
* Insert a word into the trie.
12+
*
13+
* @param word The word to insert.
14+
*/
15+
public void insert(String word) {
16+
Map<Character, TrieNode> children = root.children;
17+
18+
for (int i = 0; i < word.length(); i++) {
19+
TrieNode node;
20+
char c = word.charAt(i);
21+
22+
if (children.containsKey(c)) {
23+
node = children.get(c);
24+
} else {
25+
/**
26+
* At this point, we know if we couldn't find word.charAt(i) in our trie,
27+
* the word doesn't exist. Create a new TrieNode and populate it's child.
28+
*/
29+
node = new TrieNode();
30+
children.put(c, node);
31+
}
32+
33+
children = node.children;
34+
}
35+
36+
// Once we've reached the end of the word, mark the node as a leaf.
37+
node.endOfWord = true;
38+
}
39+
40+
/**
41+
* Lookup a word in the trie.
42+
*
43+
* @param word The word to lookup.
44+
* @return True if the trie structure contains the word.
45+
*/
46+
public boolean lookup(String word) {
47+
Map<Character, TrieNode> children = root.children;
48+
49+
/**
50+
* For each letter in the word, traverse to the deepest child found.
51+
*/
52+
for (int i = 0; i < word.length(); i++) {
53+
TrieNode node;
54+
char c = word.charAt(i);
55+
56+
if (children.containsKey(c)) {
57+
node = children.get(c);
58+
children = node.children;
59+
} else {
60+
/* If at any point a character in the word isn't found, return false as the word doesn't exist. */
61+
return false;
62+
}
63+
}
64+
return true;
65+
}
66+
67+
/**
68+
* Each node contains a hashmap of children nodes.
69+
*/
70+
static class TrieNode {
71+
Map<Character, TrieNode> children;
72+
boolean endOfWord;
73+
74+
public TrieNode() {
75+
this.children = new HashMap<>();
76+
}
77+
}
78+
79+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.