Created
May 23, 2017 11:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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