公共字串计算

一、题目(来源:点击打开链接


题目标题:

计算两个字符串的最大公共字串的长度,字符不区分大小写

详细描述:

接口说明

原型:

int getCommonStrLength(char * pFirstStr, char * pSecondStr);

输入参数:

     char * pFirstStr //第一个字符串

     char * pSecondStr//第二个字符串

 

知识点 字符串,查找
运行时间限制 10M
内存限制 128
输入

输入两个字符串

输出

输出一个整数

样例输入 asdfas werasdfaswer
样例输出 6
二、个人AC掉的代码

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <string>
#include <string.h>
using namespace std;

//KMP方法中的next表
void getNext(string needle,vector<int> &next)
{
	next[0]=-1;	
	int i=0,k=-1,size=needle.size();
	while(i<size-1)
	{
		if(k==-1 || needle[i]==needle[k])
		{
			if(needle[++i]==needle[++k])
				next[i]=next[k];
			else
				next[i]=k;
		}
		else
		{
			k=next[k];
		}
	}
}
//求最大公共字符长度
int strStr(string haystack, string needle) {
	if(haystack.empty()||needle.empty())
		return 0;
	//将大小写统一转为小写
	transform(haystack.begin(),haystack.end(),haystack.begin(),tolower);
	transform(needle.begin(),needle.end(),needle.begin(),tolower);

	int i=0,j=0,hSize=haystack.size(),nSize=needle.size(),max=0;
	vector<int> next(nSize,0);
	//获取next表
	getNext(needle,next);
	//求最大公共字符串长度
	while(i<hSize&&j<nSize)
	{
		if(j==-1||haystack[i]==needle[j])
		{
			++i,++j;
			max=max<j?j:max;//将每次求出的计算结果的最大值保存在max中
		}
		else
			j=next[j];
	}

	return max;
}
//获取两个字符串的最大长度
int getCommonStrLength(char * pFirstStr, char * pSecondStr)
{
	string haystack(pFirstStr),needle(pSecondStr);
	//若为空,则返回
	if(haystack.empty()||needle.empty())
		return 0;
	int i,size=needle.size(),max=0,tmp;
	string str;
	for(i=0;i<size;i++)
	{
		//避免从中间开始匹配麻烦,保证字符匹配是从头开始匹配的
		str=needle.substr(i);
		tmp=strStr(haystack,str);
		max=max<tmp?tmp:max;
	}

	return max;
}
int main()
{
	char haystack[1024], needle[1024];
	cin>>haystack;
	cin>>needle;

	cout<<getCommonStrLength(haystack,needle)<<endl;

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值