Skip to content

Instantly share code, notes, and snippets.

@unnisworld
Created April 10, 2019 14:37
Show Gist options
  • Save unnisworld/27eceaf9e53fc68a94d857309a6fd491 to your computer and use it in GitHub Desktop.
Save unnisworld/27eceaf9e53fc68a94d857309a6fd491 to your computer and use it in GitHub Desktop.
Trie using Array
package dsa;
import java.util.ArrayList;
import java.util.List;
public class TrieUsingArray {
TrieNode root;
TrieUsingArray() {
root = new TrieNode();
}
static class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord;
}
public void insert(String word) {
TrieNode currentNode = root;
for (int i=0;i<word.length();i++) {
char c = word.charAt(i);
int index = c - 'a';
if (currentNode.children[index] == null) {
currentNode.children[index] = new TrieNode();
}
currentNode = currentNode.children[index];
}
currentNode.isEndOfWord = true;
}
public List<String> suggest(String prefix) {
List<String> suggestions = new ArrayList<>();
TrieNode currentNode = root;
for(int i=0;i<prefix.length();i++) {
char c = prefix.charAt(i);
int index = c - 'a';
currentNode = currentNode.children[index];
if (currentNode == null) {
break;
}
}
if (currentNode != null) {
collectAllWordsUnderNode(currentNode, prefix, suggestions);
}
return suggestions;
}
private void collectAllWordsUnderNode(TrieNode node, String prefix, List<String> words) {
if(node.isEndOfWord) {
words.add(prefix);
}
for(int i=0;i<node.children.length;i++) {
if (node.children[i] != null) {
collectAllWordsUnderNode(node.children[i], prefix + (char)('a' + i), words);
}
}
}
public void display() {
internalDisplay(root, "");
}
public void internalDisplay(TrieNode node, String word) {
if (node.isEndOfWord) {
System.out.println(word);
}
for(int i=0;i<node.children.length;i++) {
if (node.children[i] != null)
internalDisplay(node.children[i], word + (char)('a' + i));
}
}
public static void main(String[] args) {
TrieUsingArray trie = new TrieUsingArray();
trie.insert("cat");
trie.insert("cam");
trie.display();
System.out.println(trie.suggest("c"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment