前綴樹
使用一個(gè)樹結(jié)構(gòu)記錄一組數(shù)據(jù),數(shù)據(jù)可以是字符串?dāng)?shù)組。
public class TrieTree {
public static class TrieNode{
public int pass;//經(jīng)過該節(jié)點(diǎn)的字符的數(shù)量
public int end;//以該節(jié)點(diǎn)為終的字符的數(shù)量
public TrieNode[] nexts;
public TrieNode(){
pass = 0;
end = 0;
//nexts[0] == null 沒有走向'a'的路
//nexts[0] 帅韧!= null 有走向'a'的路
//...
//nexts[25] 务唐!= null 有走向'z'的路
nexts = new TrieNode[26]; //HashMap<Char, Node> nexts;表示很多的字符服球,
// Char表示某個(gè)字符汛兜,Node表示下一個(gè)節(jié)點(diǎn)
//TreeMap<Char, Node> nexts;有序表
}
}
public static class Trie{
private 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++;//邊的end的pass++
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if(node.nexts[index] == null){
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.pass++;
}
node.end++;
}
//刪除前綴樹中的某個(gè)單詞,刪一個(gè)
public void delete(String word){
if(search(word) != 0){
char[] chs = word.toCharArray();
TrieNode node = root;
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 int search(String word){
if(word == null){
return 0;
}
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 0;
}
node = node.nexts[index];
}
return node.end;
}
//所有加入的字符串中,有幾個(gè)是以pre這個(gè)字符串為前綴的
public int prefixNumber(String pre){
if(pre == null){
return 0;
}
char[] chs = pre.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 0;
}
node = node.nexts[index];
}
return node.pass;
}
}
}