实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 true
trie.search(“app”); // 返回 false
trie.startsWith(“app”); // 返回 true
trie.insert(“app”);
trie.search(“app”); // 返回 true
思路不多说,裸的字典树,和三年前写的唯一区别是用Java。
由于Java中并没有指针,所以处理需要指向自己本身的类时和c++有一定区别,写这篇博客记录一下这种情况应该如何处理。
class TreeNode
{
boolean is_word;
TreeNode child[] = new TreeNode [26];
public TreeNode()//构造数组里面不要把child[]new出来,否则爆栈。
{
is_word = false;
}
}
class Trie {
TreeNode root = new TreeNode();
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
int len = word.length();
TreeNode now = root;
for(int i=0;i<len;i++)
{
char c = word.charAt(i);
if(now.child[c-'a']==null)//java中可以这么写,对象直接==null!!!
{
TreeNode n = new TreeNode();
now.child[c-'a'] = n;
}
now = now.child[c-'a'];
}
now.is_word = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
boolean find = true;
int len = word.length();
TreeNode now = root;
for(int i=0;i<len;i++)
{
char c = word.charAt(i);
if(now.child[c-'a']==null)
{
find = false;
break;
}
now = now.child[c-'a'];
}
if(find == true)
{
if(now.is_word == false)
{
find = false;
}
}
return find;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
boolean find = true;
int len = prefix.length();
TreeNode now = root;
for(int i=0;i<len;i++)
{
char c = prefix.charAt(i);
if(now.child[c-'a']==null)
{
find = false;
break;
}
now = now.child[c-'a'];
}
return find;
}
}