KMP算法(字符串匹配)
来源:互联网 发布:矩阵的模的计算公式 编辑:程序博客网 时间:2024/05/21 09:00
KMP算法
基本思想:
求next数组:
代码实现:
#include <stdio.h>#include <string.h>#include <assert.h>#include <stdlib.h>static void GetNext(const char *str,int *next){int len = strlen(str);next[0] = -1;next[1] = 0;int j = 1;int k = 0;while(j + 1 < len){if((k == -1) || (str[k] == str[j]))//Pk == Pj{next[++j] = ++k;}else//Pk != Pj{k = next[k];//k相当于KMP中的j}}}int KMP(const char *str,const char *sub,int pos)//O(m+n){assert(str != NULL && sub != NULL && pos >= 0);int i = pos;int j = 0;int lenstr = strlen(str);int lensub = strlen(sub);int *next = (int *)malloc(lensub *sizeof(int));GetNext(sub,next);while(i < lenstr && j < lensub){if((j == -1) || (str[i] == sub[j])){i++;j++;}else{j = next[j];//i不用回退}}free(next);if(j >= lensub){return i - j;}else{return -1;}}int main(){printf("%d\n",KMP("ababcabcdabcde","abcdf",0));printf("%d\n",KMP("ababcabcdabcde","abcd",4));printf("%d\n",KMP("ababcabcdabcde","abc",8));return 0;}
运行结果:
阅读全文
0 0
- KMP 字符串匹配算法
- kmp字符串匹配算法
- kmp字符串匹配算法
- KMP字符串匹配算法
- 字符串匹配算法-kmp
- KMP(字符串匹配)算法
- KMP 字符串匹配算法
- 字符串匹配算法:KMP
- KMP算法 字符串匹配
- 字符串匹配 KMP 算法
- KMP字符串匹配算法
- KMP字符串匹配算法
- KMP算法:字符串匹配
- KMP字符串匹配算法
- 字符串匹配--KMP算法
- KMP字符串匹配算法
- KMP字符串匹配算法
- KMP字符串匹配算法
- 鲜为人知的Linux命令(3)
- git commit 时 emoji 的使用
- NFS原理简述及配置
- python和flask中返回JSON数据
- 遍历Map的四种方法
- KMP算法(字符串匹配)
- React从零开始——一个详细的范例
- 自定义TabLayout,实现神奇的选项卡效果
- loongson-2F 不能升级到 Debian Stretch
- SKULib 框架实现 annotation(2)
- kafka windows安装及测试
- 微信小程序滚动Tab选项卡:左右可滑动切换
- 日期工具类
- Java 命令行及SublimeText编译环境配置(二):涉及包的编译选项