classTrie{private TrieNode root;/** Initialize your data structure here. */publicTrie(){
root =newTrieNode();}/** Inserts a word into the trie. */publicvoidinsert(String word){
TrieNode node = root;for(int i =0; i < word.length(); i++){char currentChar = word.charAt(i);if(!node.containsKey(currentChar)){
node.put(currentChar,newTrieNode());}
node = node.get(currentChar);}
node.setEnd();}// search a prefix or whole key in trie and// returns the node where search endsprivate TrieNode searchPrefix(String word){
TrieNode node = root;for(int i =0; i < word.length(); i++){char curLetter = word.charAt(i);if(node.containsKey(curLetter)){
node = node.get(curLetter);}else{return null;}}return node;}/** Returns if the word is in the trie. */publicbooleansearch(String word){
TrieNode node =searchPrefix(word);return node != null && node.isEnd();}/** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix){
TrieNode node =searchPrefix(prefix);return node != null;}}classTrieNode{// R links to node childrenprivate TrieNode[] links;privatefinalint R =26;privateboolean isEnd;publicTrieNode(){
links =newTrieNode[R];}publicbooleancontainsKey(char ch){return links[ch -'a']!= null;}public TrieNode get(char ch){return links[ch -'a'];}publicvoidput(char ch, TrieNode node){
links[ch -'a']= node;}publicvoidsetEnd(){
isEnd =true;}publicbooleanisEnd(){return isEnd;}}/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/