classTrie { privateclassNode{ publicboolean isWord; //是否是一个完整单词 public Node[] next;
publicNode(boolean isWord){ this.isWord = isWord; next = newNode[26]; }
publicNode(){ this(false); } }
private Node root;
/** Initialize your data structure here. */ publicTrie() { root=newNode(); } /** Inserts a word into the trie. */ publicvoidinsert(String word) { insert(root,word,0); } publicvoidinsert(Node cur,String word,int index){ if (index==word.length()) { if (!cur.isWord) { cur.isWord=true; } return; } char c=word.charAt(index); if (cur.next[c-'a']==null) { cur.next[c-'a']=newNode(); } insert(cur.next[c-'a'],word,index+1); //尾递归 }
/** Returns if the word is in the trie. */ publicbooleansearch(String word) { return search(root,word,0); } publicbooleansearch(Node cur,String word,int index){ if (index==word.length()) { return cur.isWord; } char c=word.charAt(index); return cur.next[c-'a']!=null&& search(cur.next[c-'a'],word,index+1); } /** Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix) { return startsWith(root,prefix,0); } publicbooleanstartsWith(Node cur,String prefix,int index){ if (index==prefix.length()) { returntrue; } char c=prefix.charAt(index); return cur.next[c-'a']!=null && startsWith(cur.next[c-'a'],prefix,index+1); } }
/** * 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); */
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ publicbooleansearch(String word) { return search(root,word,0); }
//a p p l e publicvoidinsert(Node cur,String key, int val,int index) { if (index==key.length()) { cur.isWord=true; cur.value=val; return; } char c=key.charAt(index); if (cur.next[c-'a']==null) { cur.next[c-'a']=newNode(0); } insert(cur.next[c-'a'],key,val,index+1); } publicintsum(String prefix) { return sum(root,prefix,0); }