Trie:Trie这种数据结构主要应用在搜索字符串上。比如要想查询一个字符串是否存在数组中。可以用到的集合可以是TreeMap,TreeMap这种数据结构的特点是就算是最好的满二叉树,达到的时间复杂度也会是O(logn)。而Trie是这样一种数据结构,它的时间复杂度可以与要存入的数据量无关,只与要查询的字符串的长度有关。举例来说,这种数据结构的节点可以只包括两个变量{isWorld 和 next}。next是个TreeMap结构的数据结构<Charcter,Node>。key为一个字符,而value为下一个Node的地址。这样就可以将一个字符串连接起来。所以,搜索的时候可以只搜索到字符串的长度就可以了。而这种数据结构所带来的不好的就是会造成很大的空间的浪费。
public class Trie {
//首先创建节点
private class Node{
//代表是否是单词的标志
public boolean isWorld;
//代表是否出现过这个字母,以及这个字母后面所指向的另一个节点的位置。
public TreeMap<Character,Node> next;
public Node(boolean isWorld) {
this.isWorld = isWorld;
next = new TreeMap<>();
}
public Node() {
this(false);
}
}
//创建属于这个类的变量,首先是根节点
public Node root;
//创建一个变量,记录有多少个单词
public int size;
//创建构造函数,不需要传参数,因为只需要创建一颗trie
public Trie() {
root = new Node();
size = 0;
}
//创建一个获取存了多少单词的方法
public int getSize() {
return size;
}
//创建一个添加单词的方法
public void add(String str) {
Node cur = root;
for(int i = 0;i<str.length();i++) {
char c = str.charAt(i);
if(cur.next.get(c) == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
if(cur.isWorld == false) {
cur.isWorld = true;
size++;
}
}
//查询某个单词是否存在其中
public boolean contains(String str) {
Node cur = root;
for(int i = 0;i<str.length();i++) {
char c = str.charAt(i);
if(cur.next.get(c)==null) {
return false;
}
cur = cur.next.get(c);
}
return cur.isWorld;
}
//带有通配符的查询
public boolean search(String str) {
return match(root,str,0);
}
private boolean match(Node root,String str,int index) {
if(index == str.length()) {
return root.isWorld;
}
char c = str.charAt(index);
if(c !='.') {
if(root.next.get(c) == null)
return false;
return match(root.next.get(c),str,index+1);
}
else {
for(char key:root.next.keySet()) {
if(match(root.next.get(key),str,index+1)) {
return true;
}
}
return false;
}
}
}