剪花布条---hdu2087(kmp模板)

时间:2022-11-04 14:55:42

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087

kmp模板题:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define N 1100 char s1[N], s2[N];
int p[N], L1, L2; void Getp()
{
int i=, j=-;
p[] = -;
while(i<L2)
{
if(j==- || s2[i]==s2[j])
{
i++;j++;
p[i] = j;
}
else
j = p[j];
}
} int kmp()
{
int i=, j=, ans = ;
while(i<L1)
{
if(j==- || s1[i] == s2[j])
{
i++;
j++;
}
else
{
j = p[j];
}
if(j==L2)
{
ans++;
j=;
}
}
return ans;
} int main()
{
while(scanf("%s%s", s1, s2), strcmp(s1, "#"))
{
L1 = strlen(s1);
L2 = strlen(s2);
Getp();
int ans = kmp();
printf("%d\n", ans);
}
return ;
}

kmp

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define N 2100
using namespace std; int main()
{
char s1[N],s2[N];
int len1,len2,i,j,ans;
while(scanf("%s",s1),strcmp(s1,"#"))
{
scanf("%s",s2);
len2=strlen(s2);
len1=strlen(s1);
if(len1<len2)
{
printf("0\n");
continue;
}
else
{
ans=;
i=j=;
while()
{
if(s1[i]!=s2[j])
i++;
while(s1[i]==s2[j]&&j<len2&&i<len1)
{
i++;
j++;
}
if(j==len2)
ans++;
if(i==len1)
break;
j=;
}
printf("%d\n",ans);
}
}
return ;
}

普通方法