classTrie{/** Initialize your data structure here. */classTrieNode{// 判断是否是word的结尾privateboolean isEnd;// 存储子节点privateHashMap<Character,TrieNode> map;publicTrieNode(){
isEnd=false;
map=newHashMap<>();}publicbooleangetIsEnd(){return isEnd;}publicvoidsetIsEnd(boolean isEnd){this.isEnd=isEnd;}publicTrieNodegetTrieNode(char c){return map.get(c);}publicvoidaddTrieNode(char c,TrieNode trieNode){
map.put(c, trieNode);}}privateTrieNode root;publicTrie(){
root=newTrieNode();}/** Inserts a word into the trie. */publicvoidinsert(String word){TrieNode tmp=root;// 从根节点开始遍历for(int i =0;i<word.length();i++){char c = word.charAt(i);TrieNode next=tmp.getTrieNode(c);// 如果没找到则新创建一个节点if(next==null){
next=newTrieNode();
tmp.addTrieNode(c,next);}
tmp=next;}// 遍历结束,设置当前字符为结尾
tmp.setIsEnd(true);}/** Returns if the word is in the trie. */publicbooleansearch(String word){TrieNode tmp=root;for(int i =0;i<word.length();i++){char c = word.charAt(i);TrieNode next=tmp.getTrieNode(c);// 如果子节点不存在则未找到if(next==null){returnfalse;}
tmp=next;}// 虽然成功遍历完所有字符,但还要看看是否是word结尾return tmp.getIsEnd();}/** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix){TrieNode tmp=root;for(int i =0;i<prefix.length();i++){char c = prefix.charAt(i);TrieNode next=tmp.getTrieNode(c);if(next==null){returnfalse;}
tmp=next;}// 成功遍历完所有prefix字符returntrue;}}/**
* 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);
*/