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

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

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

第一题的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/

你可能感兴趣的文章
node-static 任意文件读取漏洞复现(CVE-2023-26111)
查看>>
Node.js 8 中的 util.promisify的详解
查看>>
node.js debug在webstrom工具
查看>>
Node.js RESTful API如何使用?
查看>>
node.js url模块
查看>>
Node.js Web 模块的各种用法和常见场景
查看>>
Node.js 之 log4js 完全讲解
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 函数计算如何突破启动瓶颈,优化启动速度
查看>>
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
Node.js 异步模式浅析
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
Node.js 模块系统的原理、使用方式和一些常见的应用场景
查看>>
Node.js 的事件循环(Event Loop)详解
查看>>
node.js 简易聊天室
查看>>