POJ 3461 Oulipo KMP算法题解
来源:互联网 发布:东方财富网 mac 编辑:程序博客网 时间:2024/05/20 13:04
本题就是给出很多对字符串,然后问一个字符串在另外一个字符串出现的次数。
就是所谓的Strstr函数啦。
Leetcode有这道几乎一模一样的题目。
使用KMP算法加速,算法高手必会的算法了。
另外看见讨论说什么使用KMP还超时,最大可能是没有真正理解next table的含义,写了错误的代码,故此虽然自己运行结果正确,但是却没有真正发挥next table的作用,使得算法退化为暴力法了,所以运行正确,但超时。
KMP参考: http://blog.csdn.net/kenden23/article/details/14178121
#include <stdio.h>#include <string.h>const int MAX_N = 10001;const int MAX_T = 1000001;char word[MAX_N];char text[MAX_T];int nextTbl[MAX_N];int wn, tn;int getTimes(){int ans = 0;int i = 0, j = 0;//i为text的当前下标,j为word的当前下标for (; i-j <= tn-wn; i++){if (text[i] == word[j]){j++;if (j == wn){ans++;j = nextTbl[j-1];}}else if (j > 0){j = nextTbl[j-1];i--;}}return ans;}void genTbl(){memset(nextTbl, 0, sizeof(int) * (wn));int i = 1, j = 0;while (i < wn){if (word[i] == word[j]) nextTbl[i++] = ++j;else if (j > 0) j = nextTbl[j-1];else i++;}}int main(){int T;scanf("%d", &T);getchar();while (T--){gets(word);//fgets(word, MAX_N, stdin);//fgets会在末尾保留'\n'gets(text);//fgets(text, MAX_T, stdin);wn = strlen(word);tn = strlen(text);genTbl();printf("%d\n", getTimes());}return 0;}
1 0
- POJ 3461 Oulipo KMP算法题解
- poj 3461 Oulipo KMP算法
- poj 3461 Oulipo KMP算法
- 【POJ】【P3461】【Oulipo】【题解】【KMP】
- Poj 3461 Oulipo(KMP算法)
- POJ 3461 Oulipo (KMP算法)
- poj 3461 Oulipo(KMP 字符串匹配算法)
- kmp算法(POJ 3461 Oulipo)
- poj 3461 Oulipo 字符串匹配 KMP算法
- POJ 3461&& hiho1015 Oulipo [KMP算法]
- KMP算法 学习例题 POJ 3461Oulipo
- poj 3461 Oulipo(KMP)
- POJ 3461 Oulipo(KMP)
- POJ 3461 Oulipo---kmp
- POJ 3461 Oulipo KMP
- poj 3461 Oulipo (KMP)
- POJ 3461 Oulipo ( KMP )
- POJ 3461 Oulipo KMP
- 编程之美hiho一下求最长回文串的长度
- 基于IOS的FTP详解(五)删除文件或者目录
- R语言设置 坐标轴刻度
- ubuntu 安装五笔拼音输入法
- 为什么说IP和UDP是不可靠的,而TCP是可靠的
- POJ 3461 Oulipo KMP算法题解
- android 学习
- JavaScript--基于对象的脚本语言学习笔记(二)
- POJ1065 - Wooden Sticks - 贪心算法
- 正则表达式
- 详解openstack命令启动实现流程及原理(nova --debug image-list)
- OpenUI5 (SAPUI5) js框架简单介绍
- 最新安卓例子分类源码打包下载
- ECharts使用心得