codevs 1204寻找子串位置(kmp算法)

来源:互联网 发布:大数据4v 编辑:程序博客网 时间:2024/05/29 20:01

题目链接:http://codevs.cn/problem/1204/

代码:

#include <bits/stdc++.h>using namespace std;const int maxn=105;char a[maxn],b[maxn];int nextt[maxn];int n,m;void getnext(char str[maxn], int nextt[maxn]) {    int j = 0, k = -1;    nextt[0] = -1;    while (j < m) {        if (k == -1 || str[j] == str[k]) {            j++;            k++;            nextt[j] = k;        }        else            k = nextt[k];    }}void kmp(char a[maxn], char b[maxn]) {        int nextt[maxn];        int i = 0, j = 0;        getnext(b, nextt);        while (i < n) {            if (j == -1 || a[i] == b[j]) { // 母串不动,子串移动                j++;                i++;            }            else {                // i不需要回溯了                // i = i - j + 1;                j = nextt[j];            }            if (j == m) {                printf("%d\n", i - m + 1); // 母串的位置减去子串的长度+1                return;            }        }        printf("-1\n");}    int main(){while(cin>>a>>b){n=strlen(a);m=strlen(b);kmp(a,b);}return 0;}