思路:
无
class TrieNode {
// Initialize your data structure here.
TrieNode charecters[];
boolean end;
public TrieNode() {
charecters=new TrieNode[26];
end=false;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
root.charecters=new TrieNode[26];
}
// Inserts a word into the trie.
public void insert(String word) {
int n=word.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{
if(temp.charecters[word.charAt(i)-'a']==null)
{
temp.charecters[word.charAt(i)-'a']=new TrieNode();
}
temp=temp.charecters[word.charAt(i)-'a'];
}
temp.end=true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
int n=word.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{
if(temp.charecters[word.charAt(i)-'a']==null)
{
return false;
}
temp=temp.charecters[word.charAt(i)-'a'];
}
return temp.end;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
int n=prefix.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{
if(temp.charecters[prefix.charAt(i)-'a']==null)
{
return false;
}
temp=temp.charecters[prefix.charAt(i)-'a'];
}
if(temp.end)
{
return true;
}
for(int i=0;i<26;i++)
{
if(temp.charecters[i]!=null)
{
return true;
}
}
return false;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");