写程序比较Brute-Force算法和KMP算法的效果。
SeqString.h
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef char DataType;
#define MAXLEN 100
typedef struct Squeue{
DataType str[MAXLEN];
int len;
}SeqString;
//串的赋值
void StrAssign(SeqString *S,DataType cstr[]){
int i=0;
for(i=0;cstr[i]!='\0';i++){
S->str[i]=cstr[i];
}
S->len=i;
}
//判断串是否为空
int StrEmpty(SeqString S){
if(S.len==0)
return 1;
else
return 0;
}
//串的长度
int StrLength(SeqString S){
return S.len;
}
//串的复制
void StrCopy(SeqString *T,SeqString S){
int i;
for(i=0;i<S.len;i++){
T->str[i]=S.str[i];
}
T->len=S.len;
}
//串的比较操作
int StrCompare(SeqString S,SeqString T){
int i;
for(i=0;i<S.len;i++){
if(S.str[i]!=T.str[i]){
return (S.str[i]-T.str[i]);
}
}
return (S.len-T.len);
}
//串的插入操作
int StrInsert(SeqString *S,int pos,SeqString T){
int i;
if(pos<0||pos-1>S->len){
printf("插入位置不正确\n");
return 0;
}
//第一种情况,插入子串后串长<=MAXLEN,即子串T完整地插入到串S中
if(S->len+T.len<=MAXLEN){
for(i=S->len+T.len-1;i>=pos+T.len-1;i--){
S->str[i]=S->str[i-T.len];
}
for(i=0;i<T.len;i++){
S->str[pos+i-1]=T.str[i];
}
S->len=S->len+T.len;
return 1;
}
//第2种情况,子串可以完全插入到S中,但是S中的字符将会被截掉
else if(pos+T.len<=MAXLEN){
for(i=MAXLEN-1;i>T.len+pos-1;i--){
S->str[i

本文通过两个例子对比了Brute-Force算法与KMP算法在字符串匹配中的表现,展示了不同算法的比较次数,揭示了KMP算法在效率上的优势。
最低0.47元/天 解锁文章
2464

被折叠的 条评论
为什么被折叠?



