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

来源:互联网 发布:linux svn 当前版本号 编辑:程序博客网 时间:2024/06/08 15:18

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

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

Input

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

Output

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

Example Input

abca12345645abcddd

Example Output

14-1

Hint

 

Author



#include <iostream>#include <string.h>using namespace std;int next[1000010];void getnext(char s2[], int len2){    int i = 0, j = -1;    next[0] = -1;    while(i < len2)    {        if(j == -1 || s2[i] == s2[j])        {            i++;            j++;            next[i] = j;        }        else            j = next[j];    }}int kmp(char s1[], char s2[], int len1, int len2){    int i = 0, j = 0;    getnext(s2, len2);    while(i < len1 && j < len2)    {        if(j == -1 || s1[i] == s2[j])        {            i++;            j++;        }        else            j = next[j];    }    if(j >= len2)        return i - len2 + 1;    else        return -1;}int main(){    char s1[1000010], s2[1000010];    while(cin >> s1)    {        cin >> s2;        int len1 = strlen(s1);        int len2 = strlen(s2);        int x = kmp(s1, s2, len1, len2);        cout << x << endl;    }    return 0;}


0 0
原创粉丝点击