poj Oulipo(KMP)

本文介绍了一种使用KMP算法解决字符串匹配问题的方法。针对两个字符串ch1和ch2,通过KMP算法高效地找出ch2中与ch1相匹配的所有子串的位置。文章提供了完整的C++代码实现,并通过POJ在线评测系统的题目进行验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目连接:http://poj.org/problem?id=3461

题意:有两个字符串,ch1,ch2(strlen(ch1)<=strlen(ch2));求ch2中有多少个子串和ch1相同

解题思路:如果单纯的用string里面的find()函数的话特定超时,所以可以用kmp算法。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
#define M 10001
int t[M];
string s,ch;
void next()
{
	int x=s.length();int k=-1;t[0]=-1;
	for(int i=1;i<x;i++)
	{
		while(k>-1&&s[i]!=s[k+1])k=t[k];
		if(s[i]==s[k+1])k++;
		t[i]=k;
	}
}
void KMP()
{
	int sum=0;int m=0;int x=ch.length();
	int j=-1;int flat=0;
	for(int i=m;i<x;i++)
	{
		while(j>-1&&ch[i]!=s[j+1])j=t[j];
		if(ch[i]==s[j+1])j++;
		if(j==s.length()-1){j=t[j];sum++;}
	}
	cout<<sum<<endl;
}
int main()
{
	int n;cin>>n;
	while(n--)
	{
		cin>>s>>ch;
		next();KMP();
	}
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值