public class TrieTree {
public static class TrieNode {
public int pass;//通过当前node的次数
public int end;//以当前node为尾巴的字符串个数
public TrieNode[] nexts; //HashMap<Char,Node> nexts;
public TrieNode() {
pass = 0;
end = 0;
//nexts[0] ==null 没有走向'a'的路
//nexts[0] !=null 有走向'a' 的路
//...
//nexts[25]!=null 有走向'z' 的路
nexts = new TrieNode[26];
}
}
public static class Trie {
private static TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
if (word == null) {
return;
}
char[] chs = word.toCharArray();
TrieNode node = root;
node.pass++;
int index = 0;
for (int i = 0; i < chs.length; i++) { //从左往右遍历字符
index = chs[i] - 'a';//由字符对应成走向哪条路 a-a = 0, b-a = 1 通过相减来确定字母的索引 26个字母
if (node.nexts[index] == null) {
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.pass++;
}
node.end++;
}
//删除掉前缀树中的word
public void delete(String word) {
char[] chs = word.toCharArray();
TrieNode node = root;
if (search(word)) {//确定树中确实加入过word,才删除
node.pass--;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (--node.nexts[index].pass == 0) {
node.nexts[index] = null;
return;
}
node = node.nexts[index];
}
node.end--;
}
}
//
//查找前缀树中有没有word这个数
public static boolean search(String word) {
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.nexts[index] == null) {
return false;
}
if (i == chs.length - 1 && node.nexts[index].end == 0) {
return false;
}
node = node.nexts[index];
}
return true;
}
}
public static void main(String[] args) {
String[] arr = {"abc", "adc", "ad", "ap"};
Trie trie = new Trie();
trie.root = new TrieNode();
for (String s : arr) {
trie.insert(s);
}
boolean ad = trie.search("abc");
trie.delete("abc");
boolean ac = trie.search("abc");
System.out.println(ac);
}
}
算法基础部分-前缀树
最新推荐文章于 2024-07-24 20:44:05 发布