Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
这道题考察的就是字典树的构造,本题是使用HashMap来完成构造,说实话之前没有学过字典树俄构造,这也算第一次吧,不过这个数据结构真的很棒。
本题给我的最大的启发就是注意使用HashMap等数据结构。
代码如下:
import java.util.HashMap;
import java.util.Map;
/*
* 字典树,这个需要好好学习
* http://blog.csdn.net/xudli/article/details/45598337
* 记着吧
* */
class TrieNode
{
char c;
boolean isLeaf=false;
Map<Character, TrieNode> childred=new HashMap<Character, TrieNode>();
public TrieNode(char d)
{
c=d;
}
public TrieNode()
{
}
}
public class Trie
{
TrieNode root=null;
/** Initialize your data structure here. */
public Trie()
{
root=new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word)
{
Map<Character, TrieNode> childred=root.childred;
for(int i=0;i<word.length();i++)
{
char c=word.charAt(i);
TrieNode one=null;
if(childred.containsKey(c))
one=childred.get(c);
else
{
one=new TrieNode(c);
childred.put(c, one);
}
childred=one.childred;
if(i==word.length()-1)
one.isLeaf=true;
}
}
/** Returns if the word is in the trie. */
public boolean search(String word)
{
TrieNode res=searchNode(word);
if(res!=null && res.isLeaf)
return true;
else
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix)
{
TrieNode res=searchNode(prefix);
if(res!=null)
return true;
else
return false;
}
private TrieNode searchNode(String word)
{
TrieNode res=null;
Map<Character, TrieNode> childred=root.childred;
for(int i=0;i<word.length();i++)
{
char c=word.charAt(i);
if(childred.containsKey(c)==false)
return null;
else
{
res=childred.get(c);
childred=res.childred;
}
}
return res;
}
}
/**
* 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);
*/