package com.inspire.chapter5;
public class TrieTree {
public static class Node1 {
public int pass;
public int end;
public Node1[] nexts;
public Node1() {
pass = 0;
end = 0;
/*
* 0 a
* 1 b
* .. ..
* 25 z
* nexts[i]=null i方向的路不存在
* nexts[i]!=null i方向的路存在
*/
nexts = new Node1[26];
}
}
public static class Trie1 {
private Node1 root;
public Trie1() {
root = new Node1();
}
// 插入字符串
public void insert(String word) {
if (word == null) {
return;
}
char[] str = word.toCharArray();
Node1 node = root;
node.pass++;
int path = 0;
for (int i = 0; i < str.length; i++) {// 從左往右遍歷字符
path = str[i] - 'a';// 由字符對應成走那條路
if (node.nexts[path] == null) {
node.nexts[path] = new Node1();
}
node = node.nexts[path];
node.pass++;
}
node.end++;
}
// 查詢指定字符串出現的次數
public int search(String word) {
if (word == null) {
return 0;
}
char[] str = word.toCharArray();
Node1 node = root;
int index = 0;
for (int i = 0; i < str.length; i++) {
index = str[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.end;
}
// 所有加入的字符串中,有幾個是以pre這個字符串作爲前綴的
public int prefixNumber(String pre) {
if (pre == null) {
return 0;
}
char[] str = pre.toCharArray();
Node1 node = root;
int index = 0;
for (int i = 0; i < str.length; i++) {
index = str[i] - 'a';
if (node.nexts[index] == null) {
return 0;
}
node = node.nexts[index];
}
return node.pass;
}
//刪除指定字符串
public void delete(String word) {
if (search(word) != 0) {
char[] str = word.toCharArray();
Node1 node = root;
node.pass--;
int path = 0;
for (int i = 0; i < str.length; i++) {
path = str[i] - 'a';
if (--node.nexts[path].pass == 0) {
node.nexts[path] = null;
return;
}
node = node.nexts[path];
}
node.end--;
}
}
}
public static void main(String[] args) {
Trie1 trie1=new Trie1();
String[] str={"abc","abcd","dfg","ddd","abc"};
for(int i=0;i<str.length;i++){
trie1.insert(str[i]);
}
trie1.delete("abc");
int n=trie1.search("abc");
System.out.println(n);
}
}
數據結構與算法(JAVA版)5_1:前綴樹Part1:插入範圍限定在26個小寫字母
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.