BM算法核心思想是一一比较,失败就回溯。
#include<stdio.h>
int StrIndex_BF(char *s,char *t)//the length of the string is put in the o position
{
int i=1,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]);//if found,return the position the t-string appears
else
return -1;
}
}
KMP算法核心思想是匹配失败之后,如何将待匹配子串不回溯而直接向右滑动。即求得next位置。
#inlcude<stdio.h>
#define 100 MAXSIZE
int next[MAXSIZE];
void getNext(char*t,int next[])//compute next
{
int i=1,j=0;
next[1]=0;
while(i<t[0])
{
if(j==0||t[i]==t[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}
int StrIndex_KMP(char *s,char *t,int pos)//the length of the string is put in the o position
{
int 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-t[0]);//if found,return the position the t-string appears
else
return -1;
}
}