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

来源:互联网 发布:python求平均值函数 编辑:程序博客网 时间:2024/06/10 18:32

Problem Description

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

Input

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

Output

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

Example Input

abc
a
123456
45
abc
ddd

Example Output

1
4
-1

KMP:
用于在目标串中查找模式串。
如果目标串中有多个模式串,输出的位置是第一个位置。
1.取得next[]数组的方法:
注意:在SDUT中next[] 数组不能起名为next,否则 Compile Error;

//改进之前void get_next(char str2[])  //对模式串进行操作{    int n = strlen(str2);  //模式串的长度     int i=0;    int j=-1;    book[0] = -1;    while(i < n)    {        if(j == -1||str2[i] == str2[j])          {            i++;            j++;            book[i] = j;        }        else            j = book[j];    }}
//改进后的void get_next(char str2[]){    int n = strlen(str2);    int i=0;    int j=-1;    book[0] = -1;    while(i < n)    {        if(j == -1||str2[i] == str2[j])        {            i++;            j++;            if(str2[i] != str2[j])                book[i] = j;            else                book[i] = book[j];        }        else            j = book[j];    }}

2.KMP函数:查找模式串在目标串中的位置

int KMP(char str1[],char str2[])  //对模式串与目标串同时操作{    int i = 0;    int j = 0;    int len1 = strlen(str1);    //目标串的长度    int len2 = strlen(str2);   //模式串的长度    while(i < len1 && j < len2)    //两个串都没有扫描完进行循环    {        if(j == -1 || str1[i] == str2[j])           {            i++;            j++;        }        else            j = book[j];   //i不变,j后退(即 模式串右滑)    }    if(j >= len2)    //当模式串匹配成功        return i-len2+1;    //返回模式串在目标串中的位置    else        return -1;}

代码

#include <iostream>#include <cstring>#include <cstdio>using namespace std;char str1[1000005],str2[1000005];int book[1000005];void get_next(char str2[]){    int n = strlen(str2);    int i=0;    int j=-1;    book[0] = -1;    while(i < n)    {        if(j == -1||str2[i] == str2[j])        {            i++;            j++;            if(str2[i] != str2[j])                book[i] = j;            else                book[i] = book[j];        }        else            j = book[j];    }}int KMP(char str1[],char str2[]){    int i = 0;    int j = 0;    int len1 = strlen(str1);    int len2 = strlen(str2);    while(i < len1 && j < len2)    {        if(j == -1 || str1[i] == str2[j])        {            i++;            j++;        }        else            j = book[j];    }    if(j >= len2)        return i-len2+1;    else        return -1;}int main(){    while(scanf("%s",str1)!=EOF)    {        scanf("%s",str2);        get_next(str2);        int p = KMP(str1,str2);        printf("%d\n",p);    //p == -1说明查找失败,否则查找成功    }    return 0;}