参考文章:
https://mp.weixin.qq.com/s/hIU4gbKBNypsFWWVxx6x8Q 线段树
https://github.com/liuyubobobo/Play-with-Algorithms
https://blog.csdn.net/qq_41479464/article/details/88586512 java贪心算法(线段树)的详细介绍(强推)
https://www.cnblogs.com/TheRoadToTheGold/p/6254255.html#undefined 浅谈线段树
线段树是一个复杂的数据结构,大家如果不太懂,最好先找个视频来看看,看懂了, 再去找相关的代码或者博客去看,不然很容易迷糊的。
以下是线段树的主体实现部分:
import java.util.TreeMap;
/// 使用TreeMap的Trie
public class Trie {
private class Node{
public boolean isWord;
public TreeMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new TreeMap<>();
}
public Node(){
this(false);
}
}
private Node root;
private int size;
public Trie(){
root = new Node();
size = 0;
}
// 获得Trie中存储的单词数量
public int getSize(){
return size;
}
// 向Trie中添加一个新的单词word
public void add(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null)
cur.next.put(c, new Node());
cur = cur.next.get(c);
}
if(!cur.isWord){
cur.isWord = true;
size ++;
}
}
// 查询单词word是否在Trie中
public boolean contains(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return cur.isWord;
}
}
查询 Trie 中是否有 isPrefix 为前缀 的单词
// 查询是否在Trie中有单词以prefix为前缀
public boolean startsWith(String isPrefix){
Node cur = root;
for(int i = 0 ; i < isPrefix.length() ; i ++){
char c = isPrefix.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return true;
}