一 概念
前缀树刚开始就有一个头节点,遍历每一个字符串,构建出来头节点向每一个节点的路径。
end表示这个节点是否是尾巴节点,count表示经过这个节点的字符个数。
二 实现
TreeNode结构
Class TrieNode{
public int pass;
public int end;
public TrieNode[] nexts;
public TrieNode(){
pass = 0;
end = 0;
nexts = new TrieNode[26];
}
}
Trie树
public class Trie{
private TrieNode root;
public Trie(){
root = new TrieNode();
}
public void insert(String word){
if(word == null){
return;
}
char[] chs = word.toCharArray();
TreeNode node = root;
node.pass+;
int index = 0;
for(int i = 0; i < chs.length; i++){
index = chs[i]- 'a';
if(node.next[index] == null){
node.next[index] = new TrieNode();
}
node = node.nexts[index];
node.pass++;
}
node.end++;
}
}