KMP学习——字符串的匹配

本文深入探讨了子串查找算法的实现与应用,通过实例演示如何高效地在长字符串中定位特定子串的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Input

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

Output

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

Sample Input

abc
a
123456
45
abc
ddd

Sample Output

1
4
-1

#include <iostream>
#include"cstdio"
#include"cstring"
#include"cstdlib"
using namespace std;
char st1[1000100],st2[1000100];
int next[1000100];
int n,m;
void Kmp(char s[],char t[])
{
    int j=0,i;
    for(i=0;i<n&&j<m;)
    {
        if(j==0&&st1[i]!=st2[0]){i++;continue;}
        if(st2[j]==st1[i])
        {
            i++;j++;
            continue;
        }
        else
        {
            j=next[j];continue;
        }
    }
    if(i<=n&&j==m)printf("%d\n",i-m+1);
    else printf("-1\n");
}
int main()
{memset(st1,'\0',sizeof(st1));
 memset(st2,'\0',sizeof(st2));
 memset(next,'\0',sizeof(next));
 next[0]=-1;next[1]=0;
   while(~scanf("%s%*c%s",st1,st2))
   {n=strlen(st1);
    m=strlen(st2);
       for(int i=1;i<m-1;i++)
       {
         int  j=next[i];
           if(st2[i]==st2[j])
           next[i+1]=next[i]+1;
           else
            for(int k=next[j];j>=-1;)
          {  if(j==-1){next[i+1]=0;break;}
              if(st2[k]==st2[i])
                {next[i+1]=next[j]+1;break;}
              else
              {j=next[k];k=next[k];}
          }
       }

       Kmp(st1,st2);
   }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值