题目描述:
Implement a trie(单词查找树:利用字符串的公共前缀来节约存储空间) with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
思路:全在注释里。
public class Implement_Trie_Prefix_Tree {
public static void main(String[] args) {
Trie obj = new Trie();
obj.insert("abc");
obj.insert("acd");
obj.insert("blue");
obj.insert("boot");
obj.insert("broun");
obj.insert("cat");
obj.insert("course");
System.out.println(obj.search("abc"));
System.out.println(obj.search("acc"));
System.out.println(obj.startsWith("ac"));
System.out.println(obj.startsWith("boo"));
System.out.println(obj.startsWith("ba"));
}
}
class Trie
{
//总根节点
private TrieNode root;
/** Initialize your data structure here. */
public Trie()
{
root = new TrieNode();
}
/** Inserts a word into the trie. */
//插入操作:自上向下扫描树,如果有该节点那么就继续向下,如果没有那么就新建一个。
public void insert(String word) {
HashMap<Character, TrieNode> children = root.children;
char array[] = word.toCharArray();
for(int i=0;i<array.length;i++)
{
char chr = array[i];
TrieNode node;
if(children.containsKey(chr))
{
node = children.get(chr);
}
else
{
node = new TrieNode(chr);
children.put(chr,node);
}
children = node.children;
//将最后一个节点设置为叶子结点
if(i==array.length-1)
node.isLeaf = true;
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
//如果存在这条路径且最后一个字母为叶子结点那么存在这个word
if(SearchNode(word)!=null&&SearchNode(word).isLeaf)
return true;
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
//如果存在word这条这条分支那么有以word开头的分支
if(SearchNode(prefix)!=null)
return true;
return false;
}
//搜索自顶向下存不存在word这条分支
public TrieNode SearchNode(String word)
{
HashMap<Character, TrieNode> children = root.children;
TrieNode node = null;
char array[] = word.toCharArray();
//一路向下搜索,如果有一个节点不存在那么便不存在这条分支
for(int i=0;i<array.length;i++)
{
if(children.containsKey(array[i]))
{
node = children.get(array[i]);
children = node.children;
}
else
{
return null;
}
}
return node;
}
}
//节点类
class TrieNode
{
//该节点的值
char value;
//该点的所有子节点
HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
//是否为叶子结点
boolean isLeaf;
//总根节点不能有值
public TrieNode()
{
}
public TrieNode(char value)
{
this.value = value;
}
}
本题还有一个升级版: Add_and_Search_Word_Data_structure_design