数据结构实验之串一:KMP简单应用

    xiaoxiao2025-01-27  12

    题目描述

    给定两个字符串string1和string2,判断string2是否为string1的子串。

    输入

     输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。

    输出

     对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。

    示例输入

    abc a 123456 45 abc ddd

    示例输出

    1 4

    -1

    #include <stdio.h> #include <stdlib.h> #include<string.h> #define max 1000001 int l1,l2; int next[1000100]; char s1[1000001],s2[1000001]; void get_next(char s2[],int next[]) //求模式串T的next函数值并存入数组next中 {     int i=1;     next[1]=0;     int j=0;     l2=strlen(s2);     while(i<l2)     {         if(j==0||s2[i]==s2[j])         {             ++i;++j;             next[i]=j;         }         else             j=next[j];     } } void Index_KMP(char s1[],char s2[],int pos)//利用模式串T的next函数求T在主串S中第pos个字符之后的位置 {     int i,j;     l1=strlen(s1);     l2=strlen(s2);     i=pos;j=1;     while(i<=l1-1&&j<=l2-1)     {         if(j==0||s1[i]==s2[j]) //继续比较后续字符         {             ++i;++j;         }         else             j=next[j]; //模式串向右移动     }     if(j>l2-1) //匹配成功      printf("%d\n",i-l2+1);     else  //不成功;         printf("-1\n"); } int main() {     while(gets(s1))     {         gets(s2);         l1=strlen(s1);         l2=strlen(s2);         get_next(s2,next);        Index_KMP(s1,s2,1);     }     return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-1295821.html
    最新回复(0)