【Openjudge】字符串最大跨距

本文介绍了两种不同的字符串匹配方法:一种使用strstr函数实现简单查找;另一种则利用KMP算法完成更复杂的匹配任务。通过实例演示了如何在C++中实现这两种方法,并详细解释了其工作原理。

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

用了两个方法吧,第一种直接用strstr函数,很简单,第二种,用了kmp,比较麻烦。
#include<iostream>
#include<string.h>
using namespace std;
void revert(char []);
int main()
{
	char s[350] = {},s1[30] = {},s2[30] = {};
	cin.getline(s,330,',');
	cin.getline(s1,25,',');
	cin.getline(s2,25);
	int a,b;
	if (strstr(s,s1) == 0)
		a = -1;
	else
		a = strstr(s,s1) - s + strlen(s1);
	revert(s);//将s和s2翻转,这样就可以用strstr函数找到倒数第一个s2的位置。
	revert(s2);
	if (strstr(s,s2) == 0)
		b = -1;
	else
		b = strlen(s) - (strstr(s,s2) - s) - strlen(s2);
	if (a == -1 || b == -1)
		cout<<-1;
	else if (b - a >= 0)
		cout<<b - a;
	else
		cout<< -1;
	return 0;
}

void revert( char t[])
{
	int i = 0 ;
	int l = strlen(t);
	for (i = 0 ; i < l/2 ; i ++)
	{
		t[i] = t[l - i - 1] ^ t[i];
		t[l - i - 1] = t[l - i - 1] ^ t[i];
		t[i] = t[l - i - 1] ^ t[i];
	}
}

#include<iostream>
#include<cmath>
#include"string.h"
using namespace std;
void findnext(int next[], char p[]);
int findpos(char t[], char p[]);
int main()
{
	char s[350] =
	{ }, s1[30] =
	{ }, s2[30] =
	{ };
	cin.getline(s, 310, ',');
	cin.getline(s1, 30, ',');
	cin.getline(s2, 30);
	int a, b, t = -1;
	a = findpos(s, s1);
	//这种方法没有采用倒转的方法,而是每次都寻找一次,没找到一次s2,就把s2的第一个字符置为','(因为题目中告诉我们字符串不含有',',所以可以放心的将其置为',',这样就可以保证不会给s1中多增加一个目标字符串s2,而且不会忽略掉每一个s2)
	do
	{
		b = t;
		t = findpos(s,s2);
		s[t] = ',';

	}while (t != -1);
	if (a == -1 || b == -1)
		cout << -1;
	else if (b - a - (int)strlen(s1) >= 0)
		cout << b - a - (int)strlen(s1);
	else
		cout<< -1;
	return 0;
}

int findpos(char t[], char p[])
{
	int next[30] =
	{ };
	next[0] = -1;
	int i = 0;
	int j = 0;
	findnext(next, p);
	int l = strlen(p);
	int l2 = strlen(t);
	while (j < l && i < l2)
	{
		if (p[j] == t[i] || j == -1)
		{
			j++;
			i++;
		}
		else
		{
			j = next[j];
		}
	}
	if (p[j] == 0)
	{
		return i - strlen(p);
	}
	else
		return -1;
}

void findnext(int next[], char p[])
{
	next[0] = -1;
	int i, j;
	i = 0;
	j = -1;
	int lp = strlen(p);
	while (i < lp - 1)
	{
		while (j >= 0 && p[i] != p[j])
			j = next[j];
		j++;
		i++;
		next[i] = j;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值