/**
* @ Auther:卢宥晟
* @ Date:2019/4/30
* @ Description:algorithm_code
* @ version:1.0
*/
public class QIan_Zhui_Shu {
/**
* ------------- 前缀树-------------------------------
* 他是将各种各样的字符串连到一个串上
* 结构设计: Node int cross
* int end
* Node node[] =new Node[26]; 26个小写英文字母
* 设计思路: 传入字符串 然后转换成char数组z 得到相应数组位置,不存在的话创建,然后跳转
* 下一个char cross+1 存在直接跳转 cross+1 最终end++
*
* 功能: 1.建立前缀树
* 2.判断一个字符串出现次数 查看end值
* 3.判断是否有以某字符串为开头的 查看cross
* 4.删去一个串 cross-- end --
*
*
*/
int cross;
int end;
QIan_Zhui_Shu next[];
public QIan_Zhui_Shu() {
cross = 0;
end = 0;
next =new QIan_Zhui_Shu[26];
}
public void add(String str,QIan_Zhui_Shu next){
char temp[] =str.toCharArray();
for(int i=0;i<temp.length;i++){
int x = temp[i]-'a';
if(next.next[x]==null){
next.next[x] =new QIan_Zhui_Shu();
}
next. next[x].cross++;
if(i==temp.length-1){
next.next[x].end++;
}
next =next.next[x];
}
}
public void delete(String str,QIan_Zhui_Shu next){
char temp[] =str.toCharArray();
for(int i=0;i<temp.length;i++){
int x = temp[i]-'a';
if(next.next[x]==null){
return;
}
next.next[x].cross--;
if(i==temp.length-1){
next.next[x].end--;
}
next =next.next[x];
}
}
public int crossNum(String str,QIan_Zhui_Shu next){
char temp[] =str.toCharArray();
for(int i=0;i<temp.length;i++){
int x = temp[i]-'a';
if(next.next[x]==null){
return 0;
}
if(i==temp.length-1){
return next.next[x].cross;
}
next =next.next[x];
}
return 0;
}
public int endNum(String str,QIan_Zhui_Shu next){
char temp[] =str.toCharArray();
for(int i=0;i<temp.length;i++){
int x = temp[i]-'a';
if(next.next[x]==null){
return 0;
}
if(i==temp.length-1){
return next.next[x].end;
}
next =next.next[x];
}
return 0;
}
public static void main(String[] args) {
QIan_Zhui_Shu qIan_zhui_shu =new QIan_Zhui_Shu();
String s1= "abc";
String s2 ="ab";
String s3= "abc";
qIan_zhui_shu.add(s1,qIan_zhui_shu);
qIan_zhui_shu.add(s2,qIan_zhui_shu);
System.out.println( qIan_zhui_shu.crossNum(s2,qIan_zhui_shu));
qIan_zhui_shu.delete(s2,qIan_zhui_shu);
System.out.println( qIan_zhui_shu.crossNum(s2,qIan_zhui_shu));
System.out.println( qIan_zhui_shu.endNum(s2,qIan_zhui_shu));
}
}