第五章 串《大话数据结构》读后笔记
[第四章 栈与队列《大话数据结构》读后笔记](https://blog.csdn.net/zhengshaopeng_1/article/details/117219044
串的定义
串是由零个或者多个字符组成的有序序列,又名字符串。
朴素的模式匹配算法
一定小字符串在大字符串的模式匹配,如S=“goodgoogle” 中找 T=“google”
采用方法是对S主串进行循环,再与t的长度做小循环,知道匹配成功或者全部遍历完成为止。
int Index(String S,String T,int pos){
int pos;/*用与主串S中当前位置的下标,若pos不为1*/
int j = 1;/*T串的当前下标*/
/*S[0] T[0] 分别存了S T 的长度*/
while(i <= S[0] && j<= T[0]){
if(S[i] == T[j]){
++i;
++j;
}else{
i = i - j + 2;/*i退回到上次匹配的*/
j = 1; /*退回到首位*/
}
}
if(j > T[0])
return i-T[0];
else
return 0;
}
KMP模式匹配算法
为了解决上述朴素的模式匹配算法中重复遍历的问题。
void get_next(String T,int *next){
int i,j;
i = 1;
j = 0;
next[1] = 0;
while (i<T[0]){
if(j==0 || T[i] == T[j]){
++i;
++j;
next[i] = j;
}else{
j = next[j];
}
}
}
int Index_KMP(String S,String T,int pos){
int pos;/*用与主串S中当前位置的下标,若pos不为1*/
int j = 1;/*T串的当前下标*/
int next[255];
get_next(T,next);/*对串T作分析,得到next数组*/
/*S[0] T[0] 分别存了S T 的长度*/
while(i <= S[0] && j<= T[0]){
if(j==0 || S[i] == T[j]){
++i;
++j;
}else{
j=next[j];
}
}
if(j > T[0])
return i-T[0];
else
return 0;
}
KMP模式匹配算法改进
void get_nextval(String T,int *next){
int i,j;
i = 1;
j = 0;
nextval[1] = 0;
while (i<T[0]){
if(j==0 || T[i] == T[j]){
++i;
++j;
if(T[i] != T[j]){
nextval[i] = j;
}else{
nextval[i] = nextval[j];
}
}else{
j = nextval[j];
}
}
}