博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字符串匹配算法
阅读量:6874 次
发布时间:2019-06-26

本文共 1422 字,大约阅读时间需要 4 分钟。

字符串匹配算法有非常多种,最为经常使用的有KMP算法、普通算法。

1、普通算法:此算法是效率最低的算法。时间复杂度为O(NM)。

程序例如以下:

bool str_match(const char * str1, const char * str2)//O(P*T){	assert(str1 != NULL && str2 != NULL);	int k = 0;	for (unsigned int i = 0; i < strlen(str1); i ++)	{		k = i;		for (unsigned int j = 0; j < strlen(str2); j ++)		{			if (*(str1 + k++) == *(str2 + j))			{				if (j == strlen(str2)-1)					return true;			}			else 				break;		}	}	return false;}

2、KMP算法。KMP算法能够说是在普通算法上的改进的算法,在普通算法中,在字符串P中每一次仅仅移动一个字符,而在KMP算法中,依据后缀表达式同样的方法。能够跳过几个字符,在算法运行開始须要找出每次移动的字符数。

程序例如以下:

---------------------------------------------------KMP-------------//void findNext(const char * strP, int * next){	assert(strP != NULL && next != NULL);	int lenP = strlen(strP);	*next = -1;	int i = 0;	int j = -1;	while (i < lenP)	{		while (j == -1 || j < lenP && *(strP+i) == *(strP + j) )		{			j++;			i++;			if(*(strP+i) != *(strP + j))				next[i] = j;			else				next[i] = next[j];		}		j = next[j];	}}int KMP(const char * strP, const char *strT){	assert(strP != NULL && strT != NULL);	int lenP = strlen(strP);	int * next = new int[lenP];	findNext(strP,next);	int i = 0;	int j = 0;	int lenT = strlen(strT);	while (i <= strT-strP)	{		while (j == -1 || j < lenP && *(strP+j) == *(strT + i))		{			i++;			j++;		}		if (j == lenP)		{			return i - lenP;		}		j = *(next+j);	}	delete [] next;	return -1;}//--------------------------------------end of KMP-------------------------------------//

转载地址:http://zclfl.baihongyu.com/

你可能感兴趣的文章
Snail—OC学习之类别Category
查看>>
C#枚举的使用
查看>>
Java笔记2:Eclipse编写第一个Java程序
查看>>
opencv c++编译
查看>>
Web3.js API 中文文档
查看>>
6.计算机语言的发展 编程语言发展 编程语言类型 为什么会有编程语言 编程语言什么作用 机器语言 高级语言分类 编程语言历史 编程语言有哪些 编程语言编年史...
查看>>
Android展示控件之Surface、SurfaceView、SurfaceHolder及SurfaceHolder.Callback之间的关系
查看>>
Spark进阶之路-Standalone模式搭建
查看>>
Linux——查看系统硬件信息
查看>>
iOS instruments trace文件解析方案
查看>>
计算机_数制_码制_运算方法
查看>>
指针与句柄的区别
查看>>
C#委托-总结实例
查看>>
加密 web.config
查看>>
Linux流量监控工具-iftop教程
查看>>
ORACLE增加用户
查看>>
C#加密解密总结
查看>>
职场攻略:每天淘汰自己的不足
查看>>
帮你深入理解OAuth2.0协议
查看>>
PooledDataSource--mybatis-3-mybatis-3.2.3
查看>>