1. 程式人生 > >SDUT OJ 資料結構實驗之串二:字串匹配(KMP做法)

SDUT OJ 資料結構實驗之串二:字串匹配(KMP做法)

資料結構實驗之串二:字串匹配

Time Limit: 1000MS Memory limit: 65536K

題目描述

  給定兩個字串string1和string2,判斷string2是否為string1的子串。

輸入

 輸入包含多組資料,每組測試資料包含兩行,第一行代表string1,第二行代表string2,string1和string2中保證不出現空格。(string1和string2大小不超過100字元)

輸出

 對於每組輸入資料,若string2是string1的子串,則輸出"YES",否則輸出"NO"。

示例輸入

abc
a
123456
45
abc
ddd

示例輸出

YES
YES
NO

提示

原來的網上的程式碼做這個題都是用字元陣列做的,我就用KMP做一遍

#include<bits/stdc++.h>
using namespace std;
void GetNext(string p,int next[])
{
    int i=0,j=-1;
    next[0]=-1;
    int len2=p.size();
    while(i<len2-1)
    {
        if(j==-1||p[i]==p[j])
        {
            next[++i]=++j;
        }
        else
            j=next[j];
    }
}
int KMP(string c1,string c2)
{
    int len1=c1.size();
    int len2=c2.size();
    int i=0,j=0;
    int next[500100];
    memset(next,0,sizeof(next));
    GetNext(c2,next);
    while(i<len1&&j<len2)
    {
        if(j==-1||c1[i]==c2[j])
        {
            i++;
            j++;
        }
        else
            j=next[j];
    }
    if(j>=len2)
        return i-len2+1;
    else
        return -1;
}
int main()
{
    string c1;
    string c2;
    while(cin>>c1)
    {
        cin>>c2;
        int f=KMP(c1,c2);
        if(f==-1)
            cout<<"NO"<<endl;
        else
            cout<<"YES"<<endl;
    }
    return 0;
}