数据结构实验之串二:字符串匹配
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
#include <iostream>
#include <string.h>
using namespace std;
int next[100];
void getnext(char str[])
{
int i=0,j=-1;
next[i]=j;
int len=strlen(str);
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void kmp(char str1[],char str2[])
{
getnext(str2);
int i=0,j=0;
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<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
int main()
{
char str1[100],str2[100];
while(cin>>str1>>str2)
kmp(str1,str2);
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
int next[100];
void getnext(char str[])
{
int i=0,j=-1;
next[i]=j;
int len=strlen(str);
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void kmp(char str1[],char str2[])
{
getnext(str2);
int i=0,j=0;
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<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
int main()
{
char str1[100],str2[100];
while(cin>>str1>>str2)
kmp(str1,str2);
return 0;
}