http://acm.hdu.edu.cn/showproblem.php?pid=2203
裸的字符串匹配问题
AC代码:
#include <algorithm>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int next[200010];
char s[200010],t[100010];
void getnext(){
int i = 0, j = -1, len = strlen(t);
next[0] = -1;
while(i<len){
if(j == -1 || t[i] == t[j]){
i++,j++;
next[i] = j;
}
else
j = next[j];
}
}
bool KMP(){
int i=0, j=0;
int l1 = strlen(s), l2 = strlen(t);
while(i < l1){
if(j == -1 || s[i] == t[j]){
i++;
j++;
}
else j = next[j];
if(j >= l2) return true;
}
return false;
}
int main(){
// freopen("in.txt","r",stdin);
while(scanf("%s%s",s,t) == 2){
int l = strlen(s),tmp = l;
for(int i=0; i<tmp; i++)
s[l++] = s[i];
s[l] = '\0';
getnext();
bool ans = KMP();
ans ? cout << "yes\n" : cout << "no\n";
}
return 0;
}