SDUT-2772_数据结构实验之串一:KMP简单应用

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem 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

Hint

Source

cjx

在做KMP的题目之前,推荐先去看一下这篇博客

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int Next[1000050];
char s1[1000050],s2[1000050];

void get_next()//求next数组。
{
    int i,j,m;
    m = strlen(s2);
    i = 0;
    j = -1;
    Next[0] = -1;
    while(i<m)
    {
        if(j==-1||s2[i]==s2[j])
        {
            i++;
            j++;
            Next[i] = j;
        }
        else
            j = Next[j];
    }
}

int KMP()//KMP算法
{
    int i,j,n,m;
    n = strlen(s1);
    m = strlen(s2);
    get_next();
    i = j = 0;
    while(i<n)
    {
        if(j==-1||s1[i]==s2[j])
        {
            i++;
            j++;
        }
        else
            j = Next[j];
        if(j==m)
            return i - j + 1;
    }
    return -1;
}

int main()
{
    while(scanf("%s%s",s1,s2)!=EOF)
    {
        printf("%d\n",KMP());
    }
    return 0;
}
posted @ 2018-10-09 10:44  洛沐辰  阅读(226)  评论(0编辑  收藏  举报