[2016/12/19]kmp算法
来源:互联网 发布:淘宝青少年男装 编辑:程序博客网 时间:2024/05/17 07:34
上学期上数据结构的时候就学了这个算法,可是没好好听(摊手)。这次刷题的时候遇到了一个字符串匹配题,于是学会了这个算法。
看了这么多博客,觉得对原理讲得比较好的就是这篇:戳这里。
如果想理解,重点还是前后缀的概念。还有中间怎么跳的,这个自己写两个字符串,模拟一下就行。
下面的代码写得非常好,对理解很有帮助。为了帮助理解,加入了一些输出。
#include <iostream>#include <stdio.h> #define MAX_SIZE 1024#define ElemType charusing namespace std;void CptPfFunc( ElemType Pattern[], int PrefixFunc[] ) { register int iLen = 0; // Length of Pattern[] while( '\0' != Pattern[iLen] ) iLen++; int LOLP = 0; // Lenth of longest prefix PrefixFunc[1] = 0; for( int NOCM=2; NOCM<iLen+1; NOCM++ ) // NOCM represent the number of characters matched { while( LOLP>0 && (Pattern[LOLP] != Pattern[NOCM-1]) ) LOLP = PrefixFunc[LOLP]; if( Pattern[LOLP] == Pattern[NOCM-1] ) LOLP++; PrefixFunc[NOCM] = LOLP; printf("%d ",PrefixFunc[NOCM]); } printf("\n");} void KMPstrMatching(char Target[], char Pattern[]) { int PrefixFunc[MAX_SIZE]; register int TarLen = 0; register int PatLen = 0; // Compute the length of array Target and Pattern while( '\0' != Target[TarLen] ) TarLen++; while( '\0' != Pattern[PatLen] ) PatLen++; // Compute the prefix function of Pattern CptPfFunc(Pattern, PrefixFunc); int NOCM = 0; // Number of characters matched for( int i=0; i<TarLen; i++ ) { while( NOCM>0 && Pattern[NOCM] != Target[i] ) NOCM = PrefixFunc[NOCM]; if( Pattern[NOCM] == Target[i] ) NOCM++; if( NOCM == PatLen ) { cout<<"KMP String Matching,pattern occurs with shift "<<i - PatLen + 1<<endl; NOCM = PrefixFunc[NOCM]; } } }int main(){ KMPstrMatching("ABCVDFAB","AB");}
0 0
- [2016/12/19]kmp算法
- KMP算法详解 【KMP】
- 【KMP】KMP算法模板
- KMP hihoCoder1015 KMP算法
- **KMP算法 Problem A. cal 2016/11/12 字符串 c++
- kmp算法
- KMP算法
- KMP算法
- KMP算法
- KMP算法
- KMP 算法
- kmp算法
- KMP算法
- kmp算法
- KMP算法
- KMP算法
- kmp算法
- kmp算法
- 一点感想.
- VGG Convolutional Neural Networks Practical(6)learning a tiny CNN
- Java整型缓存
- android在6.0上的权限请求
- Angular2.0如何把CSS样式加载进组件中?
- [2016/12/19]kmp算法
- Shaderlab blend
- Android中View自定义XML属性详解以及R.attr与R.styleable的区别
- Redis安装配置
- 如何理论上从零开始设计一个去中心化的分布式数据库集群
- hibernate懒加载中的一些猫腻
- BZOJ1391: [Ceoi2008]order
- iOS 控制器多次present后返回根控制器 —— HERO博客
- HTML5综述