kmp算法 poj2752 Seek the Name, Seek the Fame
来源:互联网 发布:tvp动画软件 编辑:程序博客网 时间:2024/05/23 02:15
kmp算法是一种字符匹配算法是指给定一个字符串A和一个字符串B,问A中是否包含B。
他分两个部分:(算法不难,发代码自行体会吧)
一:先说主程序吧
代码:
//主程序j = 0;for(i = 1; i <= n; i++) { while(j > 0 && B[j+1] != A[i]) j = next[j]; if (B[j+1] == A[i]) j++; if (j == m) { printf("matching complete! jump to next[j]"); j = next[j]; //把后面的也找出来,如果找一个可以break了; }}二:预处理next数组:
代码:
//预处理next;next[1] = 0;j = 0;for(i = 2; i <= m; i++) { while(j > 0 && B[j+1] != B[i]) j = next[j]; if (B[j+1] == B[i]) j++; next[i] = j;}有没有发现这两段代码非常相似。
下面看poj的这个题目吧;这里主要与next数组的预处理非常相似/
下面直接发代码:
#include <cstdio>#include <cstring>#include <iostream>#include <cmath>#include <algorithm>const int maxn = 400008;using namespace std;char c[maxn];int next[maxn];int main() { int result[maxn]; while(~scanf("%s", c)) { memset(next, -1, sizeof(next)); next[0] = -1; int l = -1; int lc = strlen(c); for(int i = 1; i < lc; i++) { //这里注意不能写i < strlen(c);会超时,因为调用了很多次strlen函数; while(l >= 0 && c[l+1] != c[i]) l = next[l]; if (c[l+1] == c[i]) l++; next[i] = l; } int i = lc - 1; int j = 0; while(i != -1) { result[j++] = i + 1; i = next[i]; } for(int k = j-1; k >= 0; k--) printf("%d ", result[k]); printf("\n"); }return 0;}
0 0
- POJ2752 Seek the Name, Seek the Fame KMP算法
- kmp算法 poj2752 Seek the Name, Seek the Fame
- 【KMP】 poj2752 Seek the Name, Seek the Fame
- poj2752 Seek the Name, Seek the Fame--------KMP
- poj2752 Seek the Name, Seek the Fame KMP
- POJ2752 Seek the Name, Seek the Fame 【KMP】
- POJ2752 Seek the Name, Seek the Fame【KMP】
- POJ2752 Seek the Name, Seek the Fame(KMP)
- POJ2752 Seek the Name, Seek the Fame(kmp)
- 【poj2752】Seek the Name, Seek the Fame(KMP)
- 【poj2752】Seek the Name, Seek the Fame KMP
- POJ2752 Seek the Name, Seek the Fame KMP
- poj2752 Seek the Name, Seek the Fame (kmp)
- POJ2752 Seek the Name, Seek the Fame KMP应用
- 【POJ2752】Seek the Name, Seek the Fame-KMP思想
- kmp杂题3 poj2752 Seek the Name, Seek the Fame
- 【POJ2752】Seek the Name, Seek the Fame(KMP)
- poj2752 Seek the Name, Seek the Fame(KMP)
- Linux中用free命令查看内存占用情况
- class 'org.springframework.orm.hibernate3.LocalSessionFactoryBean' not found解决办法
- Android OOM分析
- HDU5914 Triangle
- oracle 集合函数
- kmp算法 poj2752 Seek the Name, Seek the Fame
- 浏览器是如何实现事件——事件的源头EventTarget
- 用变量a给出下面的定义
- 关于include的正确理解和用法
- mybatis的查询类型
- Red Hat Enterprise 6.5 在虚拟机上将系统语言修改为中文
- HDU 5649 (二分 线段树)
- 关于 ZJCPC2004第二题
- Java VisualVM 多线程监控分析工具