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");
}
}
Java实现 LeetCode 208 实现 Trie (前缀树)
原创
©著作权归作者所有:来自51CTO博客作者热爱学习的发呆哥的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【数据结构】C语言实现二叉树
【数据结构】第五章——树与二叉树详细介绍如何通过C语言实现二叉树……
数据结构 C语言 二叉树 BST -
【LeetCode】208.实现Trie(前缀树)
经典题,以防明天面试!python的代码真的比C的要简洁好多啊!
leetcode 链表 算法 子节点 后序 -
leetcode 208. 实现 Trie (前缀树)-字典树
字典树百度百科大概是一个26叉树插入每次插入的时候如果当前没有这个分支就新建节点查找每次
字典树 #include ios #define