Brute-Force经典算法和KMP算法的优劣

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

写程序比较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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨尘游子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值