博客
关于我
HDU2087,1686 KMP
阅读量:154 次
发布时间:2019-02-28

本文共 2370 字,大约阅读时间需要 7 分钟。

这两题都是统计一个字符串中另一个字符串的数量,只不过一题允许重叠,另一题不能重叠。两题在代码上最大的区别在于输入格式的处理,其实也就是找到了一个文本串和模式串匹配的子串之后,是不是从模式串开头重新找的区别。

第一题的AC代码如下:

#include 
#include
#include
using namespace std;#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);#define read(x) (x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f)void get_nxt() { ll lenb = strlen(b); int j = 0, k = -1; nxt[0] = -1; while (j < lenb) { if (k == -1 || b[j] == b[k]) nxt[++j] = ++k; else k = nxt[k]; }}ll KMP() { ll lenb = strlen(b), lena = strlen(a), res = 0; get_nxt(); ll i = 0, j = 0; while (i < lena) { if (j == -1 || a[i] == b[j]) i++, j++; else j = nxt[j]; if (j == lenb) { res++; // j = nxt[j]; j = 0; } } return res;}int main() { IOS; ll n; while (cin >> a) { if (a[0] == '#') break; cin >> b; cout << KMP() << endl; } return 0;}

第二题的AC代码如下:

#include 
#include
#include
using namespace std;#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);#define read(x) (x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f)void get_nxt() { ll lenb = strlen(b); int j = 0, k = -1; nxt[0] = -1; while (j < lenb) { if (k == -1 || b[j] == b[k]) nxt[++j] = ++k; else k = nxt[k]; }}ll KMP() { ll lenb = strlen(b), lena = strlen(a), res = 0; get_nxt(); ll i = 0, j = 0; while (i < lena) { if (j == -1 || a[i] == b[j]) i++, j++; else j = nxt[j]; if (j == lenb) { res++; j = nxt[j]; j = 0; } } return res;}int main() { IOS; ll n; cin >> n; while (n--) { if (a[0] == '#') break; cin >> b >> a; cout << KMP() << endl; } return 0;}

两题在KMP算法的实现上,最大的区别是处理匹配完成之后的逻辑。第一题在匹配完成后(即j == lenb)会将j重置为0,允许重叠匹配;而第二题则不会重置j,而是继续在当前位置寻找下一个匹配,导致不能重叠。

转载地址:http://igod.baihongyu.com/

你可能感兴趣的文章
python网络爬虫实例教程试读_Python网络爬虫实战教程(全套完整版) - 学途无忧网 - 做技术的王者 - Powered By EduSoho...
查看>>
Python 使用哈希函数用于加密
查看>>
Python 依赖管理的革新——Poetry 深度解析
查看>>
python 保留精度及增加去除数字的千位分隔符(金额化数字)
查看>>
python 倒计时 9,8,7,。。。。。。0
查看>>
Python 入门开发学习笔记之数据的增删改查
查看>>
Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
查看>>
Python 八大排序算法合集
查看>>
python 关于epoll的学习
查看>>
Python 内存管理
查看>>
Python 内嵌函数:它们有什么用处?
查看>>
Python 内置 sum 函数 vs. for 循环性能
查看>>
Python 内置时间模块
查看>>
python 内部如何实现命名元组?
查看>>
python 写入json数据到数据库
查看>>
Python 列表删除相同的元素
查看>>
Python 初学者需要知道的四条建议
查看>>
Python 判断字符串是否包含子字符串
查看>>
python 判断当前时间是否为零点
查看>>
python 利用pandas读取本地中CSV文件的指定列 列名重命名 并保存回本地
查看>>