题目大意: 给一段长度为n的整数s1以及相对较小长度为m的整数s2,问在s1中s2第一个成功匹配的位置在哪?不存在输出-1.

解题思路: kmp模板


AC代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;

int Tmp[1000001],pattern[10001],prefix[10000];

void get_prefix_table (int n) {
    int i = 0, len = -1;
    prefix[0] = -1;
    while (i < n) {
        if(len == -1 || pattern[i] == pattern[len]) {
            i++;
            len++;
            prefix[i] = len;
        }else {
            len = prefix[len];
        }
    }
}

//n : T.len, m : P.len
int kmp_search (int n, int m) {
    int i = 0, j = 0;
    get_prefix_table (m);
    while (i < n) {
        if(j == -1 || Tmp[i] == pattern[j]) {
            i++;
            j++;
        }else {
            j = prefix[j];
        }
        if(j == m) {
            return i-j+1;
        }
    }
    return -1;
}

int main() {
    int T,n,m,i;
    scanf("%d",&T);
    while (T--) {
        scanf("%d%d", &n,&m);
        for(i = 0; i < n; i++) {
            scanf("%d", &Tmp[i]);
        }
        for(i=0; i < m; i++) {
            scanf("%d", &pattern[i]);
        }
        printf("%d\n",kmp_search(n,m));
    }
    return 0;
}