數據結構實驗之串一: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

Author

cjx
#include <bits/stdc++.h>
using namespace std;

char str1[1000001],str2[1000001];
int next[10000001];

void get_next()
{
    int i,k,j;
    i=0;j=-1;
    next[0]=-1;
    while(str2[i]!='\0')
    {
        if(j==-1||str2[i]==str2[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
            j=next[j];
    }
}

void kmp()
{
    int i=0,k,j=0;

    get_next();

    int len1=strlen(str1);
    int len2=strlen(str2);

    while(i<len1&&j<len2)
    {
        if(j==-1||str1[i]==str2[j])
        {
            i++;
            j++;
        }
        else
            j=next[j];
    }
    if(j>=len2)
        cout<<i-len2+1<<endl;
    else
        cout<<-1<<endl;
}

int main()
{
    while(cin>>str1>>str2)
    {
        kmp();
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章