博客
关于我
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编程基础(附Pycharm与开发环境)
查看>>
python 如何“否定“value : 如果为真则返回假,如果为假则返回真
查看>>
Python 如何在 Web 环境中使用 Matplotlib 进行数据可视化
查看>>
python 如何把字符串转换成浮点数
查看>>
python 如果文件夹不存在就创建文件夹
查看>>
Python 如果有很多或以收缩形式
查看>>
Python 子进程 Popen 与 Pyinstaller
查看>>
Python 子进程 Popen.communicate() 等价于 Popen.stdout.read()?
查看>>
Python 子进程 Popen:为什么会出现“ls *.txt“?不行?
查看>>
Python 子进程参数
查看>>
python 字典 key 和value 互换
查看>>
Python 字典 vs If 语句速度
查看>>
python 字典sorted自定义排序,按照key or value排序
查看>>
python 字典和列表区别_元组列表和字典的主要区别是什么?
查看>>
python 字符串中特定字符替换,截取
查看>>
Python 字符串总结
查看>>
python 字符串显示中文_Python字符串开头的b"、u"、r"与中文乱码
查看>>
Python 字符串的几种拼装方式
查看>>
python 存入数据库bigint_python基础_MySQL的bigint类型
查看>>