KMP字符串匹配算法
来源:互联网 发布:讨粤匪檄 知乎 编辑:程序博客网 时间:2024/06/15 23:59
1、
KMP算法是一种线性时间复杂的字符串匹配算法,它是对BF算法(Brute-Force,最基本的字符串匹配算法的)改进。
对于给的的原始串S和模式串P,需要从字符串S中找到字符串P出现的位置的索引。
BF算法的时间复杂度O(strlen(S) * strlen(T)),空间复杂度O(1)。
KMP算法的时间复杂度O(strlen(S) + strlen(T)),空间复杂度O(strlen(T))。
2、
一个KMP算法,说白了就是构造最大后缀长度数组。
KMP算法与BF算法的区别在于,字符串失配时的处理。
KMP利用之前已经匹配好的位置,将字符串的移动次数降低,移动的步子增大。
3、
#include <iostream> #include <string>using namespace std;int kmp_find(const string& target,const string& pattern){const int pattern_length = pattern.size();const int target_length = target.size();int *overlay_function = new int [pattern_length];int index;overlay_function[0] = -1;for(int i = 1; i< pattern_length; i++){index = overlay_function[i-1];while(index >= 0 && pattern[i] != pattern[index+1] ){index = overlay_function[index];}if(pattern[i] == pattern[index+1]){overlay_function[i] = index+1;}else overlay_function[i] = -1;}//match algrithm startint target_index=0;int pattern_index=0;while(target_index < target_length&& pattern_index < pattern_length){if(target[target_index] ==pattern[pattern_index]){++target_index;++pattern_index;}else if(pattern_index == 0){++target_index;}else {pattern_index = overlay_function[pattern_index-1] + 1;}}delete [] overlay_function;if(pattern_index == pattern_length)return target_index - pattern_length;else return -1;}void main() { string source = "asdsdadwridisdaabaabcabacsdshdsads";string pattern = "abaabcabac";cout<<kmp_find(source,pattern)<<endl;}
- KMP 字符串匹配算法
- kmp字符串匹配算法
- kmp字符串匹配算法
- KMP字符串匹配算法
- 字符串匹配算法-kmp
- KMP(字符串匹配)算法
- KMP 字符串匹配算法
- 字符串匹配算法:KMP
- KMP算法 字符串匹配
- 字符串匹配 KMP 算法
- KMP字符串匹配算法
- KMP字符串匹配算法
- KMP算法:字符串匹配
- KMP字符串匹配算法
- 字符串匹配--KMP算法
- KMP字符串匹配算法
- KMP字符串匹配算法
- KMP字符串匹配算法
- Eclipse 高亮显示选中的相同变量
- android二维码扫描 ZBar
- Qt phonon多媒体框架
- linux登录模式
- 数据结构基础(一):单链表 双链表 循环链表
- KMP字符串匹配算法
- linux中文件和文件夹的添加和删除
- java (this)特殊用法
- ajax返回json数据
- Struts2零配置开发(注解Annotation的使用)二
- mysql表的复制、结构+内容查看
- 35 - Combination Sum
- iOS学习笔记01——在工程中实现ARC和MRC混合编译
- 加油