kmp算法
来源:互联网 发布:合肥淘宝包装招聘 编辑:程序博客网 时间:2024/06/16 12:03
kmp算法精髓在于next数组(我这里是nextval),而next数组的构造精髓在于模式串的自身匹配。
构造next数组:
首先 置next[0]为-1,假设对于模式串位置为i的字符匹配失败,对该字符前的字符串进行前缀和后缀的最大匹配,如果匹配失败字符和匹配的最大前缀(前缀和后缀匹配后得出)后面的字符相等, nextval[i]=nextval[j];//将模式串移到nextval[j]位置,与目的字符继续匹配 若不相等:nextval[i]=j;//将模式串移到j位置,与目的字符继续匹配
#include <iostream>#include <string>using namespace std;int KMP_Search(string & src,string &modeStr);void GetNextval(const string src,int *nextval );int main(){cout<<KMP_Search(string("abcdefgdefg"),string("de"));return 0;}void GetNextval(const string src,int *nextval ){const int srcLen=src.length();int i=0;int j=-1;nextval[0]=-1;while (i<srcLen-1){if (j==-1 || src[i]==src[j]){++j;++i;if (src[i]==src[j])nextval[i]=nextval[j];//将模式串移到nextval[j]位置,与目的字符继续匹配elsenextval[i]=j;//将模式串移到j位置,与目的字符继续匹配}elsej=nextval[j];}}int KMP_Search(string &src,string &modeStr){if (modeStr=="" || src=="")return -1;const int srcLen=src.length();const int modeStrLen=modeStr.length();//初始化next数组int *nextval=new int[modeStrLen];GetNextval(modeStr,nextval);for (int i=0,j=0; i<srcLen;){if (src[i]==modeStr[j]){++i;++j;if (j==modeStrLen){delete nextval;return i-j;}}else{if (nextval[j]==-1){j=0;++i;}elsej=nextval[j];}}delete nextval;return -1;}
- KMP算法详解 【KMP】
- 【KMP】KMP算法模板
- KMP hihoCoder1015 KMP算法
- kmp算法
- KMP算法
- KMP算法
- KMP算法
- KMP算法
- KMP 算法
- kmp算法
- KMP算法
- kmp算法
- KMP算法
- KMP算法
- kmp算法
- kmp算法
- KMP算法
- KMP算法
- Android之简洁天气
- js学习(新浪微博实习) 2 滚动照片栏的实习
- ViewPager中控件的点击事件监听
- 谈谈hashCode&equals&HashMap
- 【下载量过小,导致快传资源过期】MyEclipse 2013 SR1 下载 for Windows
- kmp算法
- 长连接 轮询
- c-krmit 9.0.302在ubuntu 12.04编译
- USB驱动编译遇到的一些问题
- Eclipse Mercurial 插件(MercurialEclipse)的安装和使用
- Stanford Algorithms: Design and Analysis, Part 1[week 1]
- 六个原则
- OGR1.10中空间叠加函数Union初探
- Unable to resolve target 'android-i'