- KMP算法是一种字符串模式匹配算法,找到主串中是否存在与子串相同的另一个子串;
void get_next(string T, int next[]) { //next数组
int i = 1, j = 0;
next[1] = 0;
while (i < T.size()) {
if (j == 0 || T.ch[i] == T.ch[j]) {
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int KMP(string S, string T) {
int i = 1, j = 1;
int next[T.size() + 1];
get_next(T, next);
while (i <= S.size() && j <= T.size()) {
if (j == 0 || S.ch[i] == T.ch[j]) {
i++;
j++;
}
else j = next[j];
}
if (j > T, size()) return i - T.size();
else return 0;
}