Skip to content

Instantly share code, notes, and snippets.

@sajith-rahim
Created January 30, 2022 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sajith-rahim/fd2776e9df3c99019dd3165284153cf4 to your computer and use it in GitHub Desktop.
Save sajith-rahim/fd2776e9df3c99019dd3165284153cf4 to your computer and use it in GitHub Desktop.
Trie Autocomplete
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TrieNode {
char c;
Map<Character, TrieNode> children;
boolean isWord;
public TrieNode(char c) {
this.c = c;
children = new HashMap<>();
}
public TrieNode() {
children = new HashMap<>();
}
public void insert(String word) {
if (word == null || word.isEmpty())
return;
char firstChar = word.charAt(0);
TrieNode child = children.get(firstChar);
if (child == null) {
child = new TrieNode(firstChar);
children.put(firstChar, child);
}
if (word.length() > 1)
child.insert(word.substring(1));
else
child.isWord = true;
}
}
public class Trie {
TrieNode root;
public Trie(List<String> words) {
root = new TrieNode();
for (String word : words)
root.insert(word);
}
public boolean find(String prefix /*,boolean exact*/) {
TrieNode lastNode = root;
for (char c : prefix.toCharArray()) {
lastNode = lastNode.children.get(c);
if (lastNode == null)
return false;
}
return lastNode.isWord;
// return !exact || lastNode.isWord;
}
/*public boolean find(String prefix) {
return find(prefix, false);
}*/
public void suggestHelper(TrieNode root, List<String> list, StringBuffer curr) {
if (root.isWord) {
list.add(curr.toString());
}
if (root.children == null || root.children.isEmpty())
return;
for (TrieNode child : root.children.values()) {
suggestHelper(child, list, curr.append(child.c));
curr.setLength(curr.length() - 1);
}
}
public List<String> suggest(String prefix) {
List<String> list = new ArrayList<>();
StringBuffer curr = new StringBuffer();
TrieNode lastNode = root;
for (char c : prefix.toCharArray()) {
lastNode = lastNode.children.get(c);
if (lastNode == null)
return list;
curr.append(c);
}
suggestHelper(lastNode, list, curr);
return list;
}
public static void main(String[] args) {
List<String> words = List.of("hello", "dog", "hell", "cat", "a", "hel","help","helps","helping");
Trie trie = new Trie(words);
System.out.println(trie.suggest("hel"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment