KMP简单应用

数据结构实验之串一:KMP简单应用
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
给定两个字符串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 <string.h>
# define MAXSIZE 1000000
char string1[MAXSIZE];
char string2[MAXSIZE];
int next[MAXSIZE];
void get_next(char str[],int len);
int kmp(char str1[],char str2[],int len1,int len2);
int main()
{
    int pos;
    int len1,len2;
    while((scanf("%s",string1))!=EOF)
    {
        scanf("%s",string2);
        len1 = strlen(string1);
        len2 = strlen(string2);
        get_next(string2,len2);
        pos = kmp(string1,string2,len1,len2);
        printf("%d\n",pos);
    }
    return 0;
}

void get_next(char str[],int len)
{
    int i,j;
    next[0] = 0;
    next[1] = 0;
    for(i = 1;i < len;i++)
    {
        j = next[i];
        while(j && str[i] != str[j])
        {
            j = next[j];
        }
        next[i+1] =  str[i] == str[j] ? j+1:0;
    }
    next[0] = -1;//不要忘了
}

int kmp(char str1[],char str2[],int len1,int len2)
{
    int i,j;
    i = j = 0;
    while(i < len1 && j < len2)
    {
        if(j == -1 || str1[i] == str2[j]) //
        {
            i++;
            j++;
        }
        else
            j = next[j];
    }
    if(j == len2)
        return i - len2 + 1;
    else
        return -1;
}

// index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//       a b d b c a b d c a b  d   c  a  b  d  d b   e

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值