数据结构实验之串二:字符串匹配
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)
Output
对于每组输入数据,若string2是string1的子串,则输出"YES",否则输出"NO"。
Example Input
abc a 123456 45 abc ddd
Example Output
YES YES NO
Hint
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
int next[1000004];
char string1[1000003] , string2[1000035] ;
void get_next(char a[],int l1)
{
int i = 0 , j = -1;
next[0] = -1;
while(i<l1)
{
if(j==-1||a[i]==a[j])
{
i++;
j++;
if(a[i]!=a[j])
{
next[i] = j ;
}
else
{
next[i] = next[j] ;
}
}
else
{
j = next[j] ;
}
}
}
int kmp(char a[] , char b[] , int l1 , int l2)
{
int i = 0 , j = 0 ;
while(i<l1&&j<l2)
{
if(j==-1||a[i]==b[j])
{
++i;
++j;
}
else
j = next[j] ;
}
if(j>=l2)
return i - l2 +1 ;
else
return -1 ;
}
int main()
{
int len1 , len2 ;
while(cin>>string1>>string2)
{
len1 = strlen(string1) ;
len2 = strlen(string2) ;
get_next(string2,len2) ;
int k = kmp(string1,string2,len1,len2) ;
if(k!=-1)
cout << "YES" << endl ;
else
cout << "NO" << endl ;
}
return 0 ;
}