题目:
实现一个 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
构成的。 - 保证所有输入均为非空字符串。
思路:
树,顾名思义 就是由根节点,子节点组成,前缀树的意思就是从根节点按顺序 依次向子节点保存值,每个节点的定义就是 是否结束和是否继续开辟固定大小空间。录入完最后一个时加上标记end 以便于区分是否结束。
如图所示,保存form,和forget两个单词的保存方法:
代码:
public class FirstTrie {
class Node{
Node[] nodes;
boolean isEnd;
public Node(){
nodes = new Node[26];
}
}
private Node root;
public FirstTrie(){
root = new Node();
}
public void insert(String word){
Node t = root;
for(int i = 0;i < word.length();i++){
int index = word.charAt(i)-'a';
if(t.nodes[index] == null){
t.nodes[index] = new Node();
}
t = t.nodes[index];//跳到子节点
}
t.isEnd = true;
}
public boolean search(String word){
Node t = root;
for(int i = 0;i < word.length();i++){
int index = word.charAt(i)-'a';
if(t.nodes[index] == null){
return false;
}
t = t.nodes[index];//跳到子节点
}
return t.isEnd == true;
}
public boolean startsWith(String word){
Node t = root;
for(int i = 0;i < word.length();i++){
int index = word.charAt(i)-'a';
if(t.nodes[index] == null){
return false;
}
t = t.nodes[index];//跳到子节点
}
return true;
}
public static void main(String[] args) {
FirstTrie m = new FirstTrie();
m.insert("from");
m.insert("tomorrow");
m.insert("on");
m.search("on");
m.startsWith("o");
}
}