class Trie {
Trie[] children=new Trie[26];
boolean isWord=false;
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
if(word.length()==0)
{
isWord=true;
return;
}
int idx=word.charAt(0)-'a';
if(children[idx]==null)
children[idx]=new Trie();
children[idx].insert(word.substring(1));
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
if(word.length()==0)
return isWord;
int idx=word.charAt(0)-'a';
if(children[idx]!=null)
return children[idx].search(word.substring(1));
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if(prefix.length()==0)
return true;
int idx=prefix.charAt(0)-'a';
if(children[idx]!=null)
return children[idx].startsWith(prefix.substring(1));
return false;
}
}
转载于:https://www.cnblogs.com/asuran/p/7796616.html