数据结构实验之串三:KMP应用

数据结构实验之串三:KMP应用

判断子串在主串中是否存在过一次,

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

int text[11234567];
int pattern[11234567];
int n,m;
void get(int pattern[], int next[])
{
    int i = 0,j = -1;
    next[0] = -1;
    while(i < n){
        if(j == -1||pattern[i]==pattern[j]){
            i++;
            j++;
            next[i] = j;
        }else{
            j = next[j];
        }
    }
}
int kmp(int text[], int pattern[])
{
    int next[n+1];
    get(pattern,next);
    int i = 0,j = 0,index = 0;
    while(i<n&&j<m){
        if(text[i]==pattern[j]){
            i++;
            j++;
        }else{
            index+=j-next[j];
            if(next[j]!=-1){
                j = next[j];
            }else{
                i++;
                j = 0;
            }
        }
    }
    if(j == m){
        return index+1;
    }else{
        return -1;
    }
}
int main()
{
    while(~scanf("%d", &n)){
        for(int i = 0;i <n;i++){
            scanf("%d", &text[i]);
        }
        scanf("%d", &m);
        for(int i = 0;i <m;i++){
            scanf("%d", &pattern[i]);
        }
        int t = kmp(text, pattern);
        if(t == -1){
            printf("-1\n");
        }else{
            int tt = kmp(text+t,pattern);
            if(tt==-1){
                printf("%d %d\n", t,t+m-1);
            }else{
                printf("-1\n");
            }
        }
    }


    return 0;
}
    原文作者:KMP算法
    原文地址: https://blog.csdn.net/qq_33435265/article/details/69461882
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞