博客
关于我
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 valueerror object2_python遇到错误记录
查看>>
python vars的作用
查看>>
Python vcrpy库:HTTP请求记录和重放
查看>>
Python virtualenv
查看>>
python vue3实现大文件分段续传(断点续传)--带暂停和继续功能
查看>>
Python WebDriver如何打印整个页面源(html)
查看>>
Python WebSocket自动化测试:构建高效接口测试框架
查看>>
Python Web开发
查看>>
Redis 配置文件杂项。
查看>>
Python web自动化测试 —— 文件上传
查看>>
Python web自动化测试 —— 文件上传!
查看>>
Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
查看>>
python win32api键盘_Python win32api.keybd_event模拟键盘输入
查看>>
python Windows显示当前鼠标坐标
查看>>
python Workbook 表格宽度
查看>>
python write报错a byte-like object is required.not str
查看>>
python yaml.dump 缩进错误
查看>>
Python yield generator
查看>>
python | authlib,一个强大的 Python 库!
查看>>
python | awswrangler,一个高效的 Python 库!
查看>>