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

最后都变了- 提交于 2020-02-19 14:57:52

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

Output 

1

4

-1

Hint

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

using namespace std;
char str1[1000001],str2[1000001];
int nex[1000001];
void getNext()
{
    int i=0,j=-1;
    nex[0]=-1;
    while(str2[i]!='\0')
    {
        if(j==-1||str2[i]==str2[j])
        {
            ++i;
            ++j;
            nex[i]=j;
        }
        else
        {
            j=nex[j];
        }
    }
}
void kmp()
{
    int len1,len2;
    len1=strlen(str1);
    len2=strlen(str2);
    int i=0,j=0;
    while(i<len1&&j<len2)
    {
        if(j==-1||str1[i]==str2[j])
        {
            ++i;
            ++j;
        }
        else j=nex[j];
    }
    if(j>=len2)
        printf("%d\n",i-len2+1);
    else printf("-1\n");
}
int main()
{
    while(gets(str1))
    {
        gets(str2);
        getNext();
        kmp();
    }
    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!