Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created a Trie implementation in Java #355

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions trie/Trie.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
private class Node {
String prefix;
HashMap<Character, Node> children;

// Does this node represent the last character in a word?
boolean isWord;

private Node(String prefix) {
this.prefix = prefix;
this.children = new HashMap<Character, Node>();
}
}

// The trie
private Node trie;

// Construct the trie from the dictionary
public Autocomplete(String[] dict) {
trie = new Node("");
for (String s : dict) insertWord(s);
}

// Insert a word into the trie
private void insertWord(String s) {
// Iterate through each character in the string. If the character is not
// already in the trie then add it
Node curr = trie;
for (int i = 0; i < s.length(); i++) {
if (!curr.children.containsKey(s.charAt(i))) {
curr.children.put(s.charAt(i), new Node(s.substring(0, i + 1)));
}
curr = curr.children.get(s.charAt(i));
if (i == s.length() - 1) curr.isWord = true;
}
}

// Find all words in trie that start with prefix
public List<String> getWordsForPrefix(String pre) {
List<String> results = new LinkedList<String>();

// Iterate to the end of the prefix
Node curr = trie;
for (char c : pre.toCharArray()) {
if (curr.children.containsKey(c)) {
curr = curr.children.get(c);
} else {
return results;
}
}

// At the end of the prefix, find all child words
findAllChildWords(curr, results);
return results;
}

// Recursively find every child word
private void findAllChildWords(Node n, List<String> results) {
if (n.isWord) results.add(n.prefix);
for (Character c : n.children.keySet()) {
findAllChildWords(n.children.get(c), results);
}
}