BF算法
int Index(SString S, SString T, int pos) {
//pos为T【1】在S串的首次出现位置,若未找到则返回0
//SString中下标为0记录着串的长度
i = pos;
j = 1;
while (i <= s[0] && j <= T[0]) {
if (S[i] == T[j]{
i++;
j++;
}
else {
i = i - j + 2;
j = 1;
}
}
if (j > T[0])return i - T[0];
else return 0;
}
KMP算法
匹配部分
int Index_KMP(SString S, SString T, int pos) {
i = pos; j = 1;
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;
}
next数组求解部分
void get_next(SString T, int next[]) {
i = 1;
next[1] = 0;
j = 0;
while (i < T[0]) {
if (j == 0 || T[i] == T[j]) {
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
next数组优化
void get_nextval(SString T, int nextval[]) {
i = 1;
nextval[1] = 0;
j = 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];
}
}
这里的next数组和串的起始下标均为1,next数组为求解最大公共前后缀后右移一位加一。