字符串匹配算法
来源:互联网 发布:信用卡还款提醒软件 编辑:程序博客网 时间:2024/06/03 16:58
字符串匹配算法有很多种,最为常用的有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;elsenext[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-------------------------------------//
0 0
- 算法 字符串匹配算法
- 字符串匹配算法
- BM字符串匹配算法
- KMP 字符串匹配算法
- 字符串匹配算法
- 字符串匹配算法
- 字符串匹配算法(摘)
- 字符串匹配算法
- 字符串匹配算法
- 字符串匹配的算法
- kmp字符串匹配算法
- 字符串匹配算法
- 字符串匹配算法研究
- 字符串模式匹配算法
- kmp字符串匹配算法
- KMP字符串匹配算法
- 字符串模式匹配算法
- BM字符串匹配算法
- Strutsw2与Spring整合流程-简述
- codeforces Round #271(div2) B解题报告
- 水樹 奈々 Blog 20140916 緊張のコラボっ!译文
- import,reload,__import__在python中的区别
- IOS开发中判断文件是否存在,不存在则拷贝
- 字符串匹配算法
- 求两个字符串公共子序列的最大长度(参考阿里巴巴2015研发笔试)(简单)
- HDUOJ_1754 I Hate it
- SQL2008 连接SQL2000 问题总结
- wholesaleinternet 服务器 配置
- 黑马程序员——开学前自学的Java课程——各章节单词一览表
- 三大运营商体验好又省钱方案
- [java]Java调用python工具类(非jython)
- NYoj-街区最短路径问题