BF算法和KMP算法
代码debug心得
1、注意输入法的调试,最好是ENG美事键盘,否则在字符串的输入上会有一些出错,过两天学习一下系统的字符串输入的各种方法;
2、注意设置MaxSize,其中因为MaxSize设置小了没注意到debug半个小时;
3、注意字符串数组开始下标,求解next数组,BF,KMP,均要保持一致,明确从0开始还是从1开始(本文从数组下标0开始,此时初始next[0] = -1);
4、next数组全局定义,否则无法在KMP中调用next,需要多一个数组空间来获取GetNext()结果。
代码如下(有错误望指正):
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <iostream>
#include <string.h>
#include <cstring>
#define ElemType int
#define MaxSize 30
using namespace std;
typedef struct{//串的数据结构定义
char ch[MaxSize];
int length;
}SString;
int next[MaxSize];
int BF(SString S,SString T){ //串匹配的BF算法,返回相匹配的第一个元素在S的序号,否则返回0
int i,j;
i=0,j=0;//i,j begins with 1,i go S,j go T
while(i<S.length && j<T.length){
if(S.ch[i] == T.ch[j]) {
++i;++j;
}
else{
i = i-j+2;
j = 1;
}
}
if(j == T.length) return i-T.length+1;
else return -1;
}
void GetNext(SString T)//人工依据算法模拟一遍是最好的理解,i不动,j回溯,i一直在j前面。
{
int i = 0, j = -1;
next[0] = -1; //******IMPORTANT!! 串下标从零开始,next[0] = -1
while(i < T.length)
{
if(j == -1 || T.ch[i] == T.ch[j])
{
next[++i] = ++j;
}
else j = next[j];
}
}
int KMP(SString S,SString T)
{
int i = 0, j = 0;
while (i < S.length && j < T.length)
{
if(j == -1 || S.ch[i] == T.ch[j])
{
j++;
i++;
}
else
j = next[j];
}
if(j == T.length) //success! j go over T
return i-j+1;
else
return -1;
}
//字符串输入,串数据结构的输入
int main(){
cout<<"===================================================="<<endl;
cout<<" BF KMP "<<endl;
cout<<"===================================================="<<endl;
clock_t start,end;
SString S; //串匹配 主串:abcbaacbabcabbcccabccab,输入
SString T; //串匹配 子串:abcabbc,输入
char s,m;
cout<<"请输入主串S:"<<endl;
for(;s!='\n';) //遇到回车就终止循环
{
cin>>S.ch;
s=getchar(); //s用来接收是否是回车
}
S.length = strlen(S.ch);
cout<<"请输入子串T:"<<endl;
for(;m!='\n';) //遇到回车就终止循环
{
cin>>T.ch;
m=getchar(); //M用来接收是否是回车
}
T.length = strlen(T.ch);
cout<<"===================================================="<<endl;
int A[MaxSize];
GetNext(T);
cout<<"子串T的next数组为:";
for(int k=0;k<T.length;k++){
cout<<next[k]<<' ';
}
cout<<endl;
int BF_ans,KMP_ans;
start = clock();
BF_ans = BF(S,T);//BF算法所得
KMP_ans = KMP(S,T);//KMP算法所得
end = clock();
cout<<"===================================================="<<endl;
cout<<"BF算法得到结果:(匹配成功后第一个元素在S中的序号): "<<BF_ans<<endl;
cout<<"===================================================="<<endl;
cout<<"KMP算法得到结果:(匹配成功后第一个元素在S中的序号): "<<KMP_ans<<endl;
cout<<"===================================================="<<endl;
cout<<"运行时间: "<<double(end-start)/CLOCKS_PER_SEC<<endl;
return 0;
}
随机调试了一组S和T,运行结果如下: