KMP

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



#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>

#define N 1000010
using namespace std;

int Next[N];
char _string1[N], _string2[N];

void creat_next(char *str)
{
    int lenth = strlen(str);
    int j = -1, k = 0;
    Next[0] = -1;
    while(k < lenth)
    {
        if(j == -1 || str[j] == str[k])
        {
            ++ j;
            ++ k;
            Next[k] = j;
        }
        else
        {
            j = Next[j];
        }
    }
}

int  _find(char *str1, char *str2)
{
    int lenth1 = strlen(str1), lenth2 = strlen(str2);
    int i = 0, j = 0;
    while(i < lenth1 && j < lenth2)
    {
        if(j == -1 || str1[i] == str2[j])
        {
            ++ j;
            ++ i;
        }
        else
            j = Next[j];
    }
    if(str2[j] == '')
    {
        return i-lenth2+1;
    }
    return -1;
}


int main()
{
    
    while(gets(_string1))
    {
        gets(_string2);
        creat_next(_string2);
        cout << _find(_string1, _string2) << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiao-xue-di/p/9400870.html