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

题目描述

给定两个字符串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; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值