arraylist实现前缀树。一开始犯了2个错误,
(1)root应该是空的,首字母从root.next开始,这样才能存多个prefix。
(2)添加词尾结束符(leaf node),不然insert(abc)之后search(ab)返回true而不是false
class TrieNode {
// Initialize your data structure here.
public TrieNode() {
next=new ArrayList<TrieNode>();
leaf=true;
}
public TrieNode(char c)
{
value=c;
next=new ArrayList<TrieNode>();
leaf=false;
}
char value;
ArrayList<TrieNode> next;
boolean leaf;
}
public class Trie {
private TrieNode root;
int size;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
if(word==null || word.length()==0)return;
int i=-1;
TrieNode current=root;
while(i<word.length()-1)
{
boolean flag=false;
for(int j=0;j<current.next.size();j++)
{
if(current.next.get(j).value==word.charAt(i+1))
{
current=current.next.get(j);
i++;
flag=true;
break;
}
}
if(flag==false)
{
TrieNode temp=new TrieNode(word.charAt(i+1));
current.next.add(temp);
current=temp;
i++;
}
}
for(int k=0;k<current.next.size();k++)
{
if(current.next.get(k).leaf==true)return;
}
current.next.add(new TrieNode());
}
// Returns if the word is in the trie.
public boolean search(String word) {
if(word==null || word.length()==0)return true;
int i=-1;
TrieNode current=root;
while(i<word.length()-1)
{
boolean flag=false;
for(int j=0;j<current.next.size();j++)
{
if(current.next.get(j).value==word.charAt(i+1))
{
current=current.next.get(j);
i++;
flag=true;
break;
}
}
if(flag==false)return false;
}
for(int k=0;k<current.next.size();k++)
{
if(current.next.get(k).leaf==true)return true;
}
return false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if(prefix==null || prefix.length()==0)return true;
int i=-1;
TrieNode current=root;
while(i<prefix.length()-1)
{
boolean flag=false;
for(int j=0;j<current.next.size();j++)
{
if(current.next.get(j).value==prefix.charAt(i+1))
{
current=current.next.get(j);
i++;
flag=true;
break;
}
}
if(flag==false)return false;
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");