Last active
May 23, 2017 09:48
-
-
Save anil477/de692974a39bf4f4f13ed19f9f56cd98 to your computer and use it in GitHub Desktop.
Longest Common Prefix
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; | |
public TrieNode() { | |
children = new HashMap<>(); | |
endOfWord = false; | |
} | |
} | |
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; | |
} | |
public void lcp() { | |
StringBuilder prefix = new StringBuilder(); | |
TrieNode current = root; | |
while(current != null && current.children.keySet().size() == 1 && !current.endOfWord){ | |
Set set = current.children.keySet(); | |
// the set will have only one key. We get that key. | |
// then parse that key to char type and use that key to lookup in Hashmap | |
String key = set.iterator().next().toString(); | |
TrieNode node = current.children.get(key.charAt(0)); | |
current = node; | |
prefix.append(key.charAt(0)); | |
} | |
System.out.println("LCP: " + prefix); | |
} | |
public static void main(String[] args) { | |
Trie object = new Trie(); | |
object.insert("docag"); | |
object.insert("docdve"); | |
object.insert("docak"); | |
object.lcp(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment