第1关:普通模式匹配(BF)算法
#include <stdio.h>
#include <string.h>
//串普通模式匹配算法的实现函数,其中 B是伪主串,A是伪子串
int mate(char * B,char *A){
/** 请在此处填写代码 **/
/********** Begin *********/
int i=0,j=0;
while(i<=strlen(B) && j<=strlen(A))
{
if(B[i]==A[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
if(j==strlen(A))
return i-strlen(A)+1;
}
/********** End **********/
}
int main() {
int number=mate("ababcabcacbab", "abcac");
printf("%d",number);
return 0;
}
第2关:快速模式匹配(KMP)算法
#include <stdio.h>
#include <string.h>
void Next(char*T,int *next){
int i=1;
next[1]=0;
int j=0;
while (i<strlen(T)) {
if (j==0||T[i-1]==T[j-1]) {
i++;
j++;
next[i]=j;
}else{
j=next[j];
}
}
}
int KMP(char * S,char * T){
/** 实现KMP算法, 若匹配返回匹配字符串长度,若不匹配返回 -1 **/
/*************** begin *******************/
int i=1,j=1;
int next[strlen(T)];
Next(T,next);
while(i <= strlen(S) && j <= strlen(T))
{
if(j == 0 || S[i-1] == T[j-1])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j > strlen(T))
return i-(int)strlen(T);
else
return -1;
/*************** end *********************/
}
int main() {
char a[1000], b[100];
scanf("%s %s", a, b);
int i = KMP(a, b);
printf("%d",i);
return 0;
}