实现一个 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
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
我所选前缀树的底层是一个数组,算是一种变相的26叉树,每个结点都有26的子树。
定义一个内部类,就是每个结点的定义他的域有对应的字符串(没插入对应单词之前为空字符串,插入后为插入的单词)和一个大小为26的数组作为子树。
class Trie {
Node root;
class Node{
String str="";
Node[] node=new Node[26];
}
/** Initialize your data structure here. */
public Trie() {
root=new Node();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node p=root; //从根节点开始
for(char c:word.toCharArray()) { //对对应的word数组进行遍历
if(p.node[c-'a']==null) { //之前没有走过这个,那么创建对应的结点
p.node[c-'a']=new Node();
}
p=p.node[c-'a']; //指针后移
}
p.str=word; //在对应的结点上放上word的字符串
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Node p=root; //从根节点开始
for(char c:word.toCharArray()) {
if(p.node[c-'a']==null) //一直没有走过这个结点一定没有单词
return false;
p=p.node[c-'a']; //后移下一结点
}
return p.str.equals(word); //看看是否有单词.
//注意如果这个结点作为前缀而不是单词,这个结只是存在但是保存的str是空字符串
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node p=root;
for(char c:prefix.toCharArray()) {
if(p.node[c-'a']==null)
return false;
p=p.node[c-'a'];
}
return true; //搜索到这里不管是作为前缀也好,单词也好总之有这个前缀
}
}