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 YESNO
#include <iostream> #include <algorithm> #include <string> #include <cstring> using namespace std; //kmp算法 int next[101]; void getnext(char s[]) { int i=0,j=-1; next[0]=-1; int len=strlen(s); while(i<len) { if(j==-1||s[i]==s[j]) { i++; j++; if(s[i]!=s[j]) next[i]=j; else next[i]=next[j]; } else j=next[j]; } } int kmp(char s1[],char s2[]) { int i,j; i=j=0; int len1=strlen(s1); int len2=strlen(s2); while(i<len1&&j<len2) { if(j==-1||s1[i]==s2[j]) { i++; j++; } else j=next[j]; } if(j==len2) return i-len2+1; else return -1; } int main() { char s1[101],s2[101]; while(cin>>s1>>s2) { getnext(s2); int x=kmp(s1,s2); if(x!=-1) cout<<"YES\n"; else cout<<"NO\n"; } return 0; }