它是一种专门处理字符串匹配的数据结构,用来解决在一组字符串集合中快速查找某个字符串的问题。bash
它的本质,就是利用字符串之间的公共前缀,将重复的前缀合并在一块儿。数据结构
如如下6个字符串:how、hi、her、hello、so、seeui
其中,根节点不包含任何信息。每一个节点表示一个字符串中的字符,从根节点到红色节点(不必定都是叶子节点)的一条路径表示一个字符串。this
Trie树的构造过程:构造的每一步,都至关于往Trie树中插入一个字符串。当全部字符串都插入完成后,Trie树就构造好了。搜索引擎
public class Trie {
private TrieNode root = new TrieNode('/'); // 存储无心义字符
// 往 Trie 树中插入一个字符串
public void insert(char[] text) {
TrieNode p = root;
for (int i = 0; i < text.length; ++i) {
int index = text[i] - 'a';
if (p.children[index] == null) {
TrieNode newNode = new TrieNode(text[i]);
p.children[index] = newNode;
}
p = p.children[index];
}
p.isEndingChar = true;
}
// 在 Trie 树中查找一个字符串
public boolean find(char[] pattern) {
TrieNode p = root;
for (int i = 0; i < pattern.length; ++i) {
int index = pattern[i] - 'a';
if (p.children[index] == null) {
return false; // 不存在 pattern
}
p = p.children[index];
}
if (p.isEndingChar == false) return false; // 不能彻底匹配,只是前缀
else return true; // 找到 pattern
}
public class TrieNode {
public char data;
public TrieNode[] children = new TrieNode[26];
public boolean isEndingChar = false;
public TrieNode(char data) {
this.data = data;
}
}
}
复制代码
插入时间复杂度O(n)(n表示全部字符串的长度和)。spa
查找时间复杂度O(k)(k表示要查找的字符串的长度)。3d
以上的数据结构形成空间复杂度很大。code