Created
June 18, 2015 03:28
-
-
Save anvaypatil/5668838f05641bd95ffa to your computer and use it in GitHub Desktop.
Trie Data Structure
This file contains hidden or 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
public class Trie { | |
private TrieNode root; | |
public Trie() { | |
this.root = new TrieNode(' '); | |
} | |
public boolean insert(String word,String meta) { | |
TrieNode iter=root; | |
TrieNode temp; | |
for(char c:word.toCharArray()){ | |
if(iter.nodes[(int)(c)]==null){ | |
temp=new TrieNode(c); | |
iter.nodes[(int)(c)]=temp; | |
iter=temp; | |
}else{ | |
iter=iter.nodes[(int)(c)]; | |
} | |
} | |
iter.meta=meta; | |
return true; | |
} | |
public String get(String word){ | |
String meta=null; | |
TrieNode iter=root; | |
for(char c:word.toCharArray()){ | |
if(iter.nodes[(int)(c)]==null){ | |
return "No Meta"; | |
}else{ | |
iter=iter.nodes[(int)(c)]; | |
} | |
} | |
return iter.meta; | |
} | |
} | |
public class TrieMain { | |
public static void main(String[] args) { | |
Trie trie=new Trie(); | |
trie.insert("Google & google","Geegal"); | |
trie.insert("Maasterer $ Ne *(&&","Global"); | |
System.out.println(trie.get("Maasterer $ Ne *(&&")); | |
} | |
} | |
class TrieNode { | |
public TrieNode[] nodes; | |
private char data; | |
public String meta; | |
public TrieNode(char cdata) { | |
nodes = new TrieNode[256]; | |
data = cdata; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment