第1关
求子串
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "SubStr.h"
void SubStr(SString t, SString s,int i,int len)
{
int m=strlen(s),j=0;
if(i+len-1>m)
printf("error");
else if(len==0)
printf("");
else
{
for(j=i;j<i+len;j++)
{
t[j-i]=s[j];
}
printf("%s",t);
}
}
第2关
串的模式匹配之简单算法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "strBF.h"
int StrIndex_BF(SString s, SString t, int pos)
{
int i=pos,j=1;
while(i<=s[0]&&j<=t[0])
{
if(s[i]==t[j])
{
i++;
j++;
}
else
{
i=i-j+2;
j=1;
}
}
if(j>t[0])
{
return i-t[0];
}
else
return 0;
}
第3关
串的模式匹配之KMP算法
/*************************************************************
date: February 2019
**************************************************************/
//´®µÄģʽƥÅäÖ®¸Ä½øËã·¨ ʵÏÖÎļþ
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "strKMP.h"
/
void GetNext(SString t, int next[])
//Çóģʽ´®TµÄnextÖµ²¢´æÈënextÊý×éÖÐ
{
int i=1,j=0;
next[1]=0;
while(i<t[0])
{
if(t[i]==t[j]||j==0)
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int StrIndex_KMP(SString s,SString t, int pos)
//²ÉÓÃKMPËã·¨£¬´ÓÖ÷´®sµÄµÚpos¸ö×Ö·û¿ªÊ¼²éÕÒ×Ó´®tµÚÒ»´Î³öÏÖµÄλÖÃ
{
int i,j,next[MAXSTRLEN+1];
GetNext(t,next);
i=pos; j=1;
while(i<=s[0]&&j<=t[0])
if(s[i]==t[j]||j==0)
{ i++; j++; }
else j=next[j]; //ģʽ´®ÏòÓÒ»¬¶¯
if(j>t[0]) return i-j+1; //Æ¥Åä³É¹¦
else return 0; //Æ¥Åäʧ°Ü
}