Skip to content

Instantly share code, notes, and snippets.

@anil477
Created May 23, 2017 11:41
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 anil477/f2aab4310e9d25197049ce45eebc4cac to your computer and use it in GitHub Desktop.
Save anil477/f2aab4310e9d25197049ce45eebc4cac to your computer and use it in GitHub Desktop.
A very basic Trie implementation to insert and search. We also maintain the frequency of each word inserted in the lead node.
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.Iterator;
class Trie {
private class TrieNode {
Map<Character, TrieNode> children;
boolean endOfWord;
int count;
public TrieNode() {
children = new HashMap<>();
endOfWord = false;
count = 0;
}
}
private final TrieNode root;
public Trie() {
root = new TrieNode();
}
/**
* Iterative implementation of insert into trie
*/
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
//mark the current nodes endOfWord as true
current.endOfWord = true;
current.count++;
}
public void search(String word) {
TrieNode current = root;
int length = word.length();
for(int i = 0; i < length; i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if(node == null){
break;
}
current = node;
}
System.out.println("Output : " + current.count);
}
public static void main(String[] args) {
Trie object = new Trie();
object.insert("are");
object.insert("area");
object.insert("base");
object.insert("cat");
object.insert("cat");
object.insert("cat");
object.insert("caterer");
object.insert("caterer");
object.insert("caterer");
object.insert("children");
object.insert("basement");
object.insert("aloha");
object.search("caterer");
object.search("aloha");
object.search("cat");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment