2432 Problem A 求最长公共子串(串)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a845717607/article/details/82079067

问题 A: 求最长公共子串(串)

时间限制: 1 Sec  内存限制: 128 MB
提交: 34  解决: 19
 

题目描述

求采用顺序结构存储的串s和串t的一个最长公共子串,若没有则输出false,若最长的有多个则输出最先出现的那一串。

输入

输入两个字符串

输出

输出公共子串

样例输入

abcdef
adbcef

样例输出

bc

经验总结

求最长公共子串(连续)的方法,可以用KMP,当然也可以用字符串hash,分别计算两个字符串的所有子串的hash值,然后一一对比,当两个字符串的hash值相等时,如果长度大于之前访问得到的公共子串长度的最大值,则更新最大值,并存储此子串的起始位置,最终得到最长的公共子串~

正确代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <iostream> 
#include <string>
using namespace std;
typedef long long LL;
const int maxn=1010;
const LL p=1e7+19;
const LL mod=1e9+7;
LL powP[maxn],H1[maxn]={0},H2[maxn]={0};

struct Node
{
	int hashValue,length,start,end;
	Node(int a,int b,int c,int d):hashValue(a),length(b),start(c),end(d){};
};
vector<Node> pr1,pr2;
void init(int len)
{
	powP[0]=1;
	for(int i=1;i<=len;++i)
	{
		powP[i]=(powP[i-1]*p)%mod;
	}
}
void calH(LL H[],string &str)
{
	H[0]=str[0];
	for(int i=1;i<str.length();++i)
	{
		H[i]=(H[i-1]*p+str[i])%mod;
	}
}
int calSingleSubH(LL H[],int i,int j)
{
	if(i==0)
		return H[j];
	return ((H[j]-H[i-1]*powP[j-i+1])%mod+mod)%mod;
}
void calSubH(LL H[],int len,vector<Node> &p)
{
	for(int i=0;i<len;++i)
		for(int j=i;j<len;++j)
		{
			int value=calSingleSubH(H,i,j);
			p.push_back(Node(value,j-i+1,i,j));
		}
}
string getMax(string str1)
{
	string str;
	int ans=0;
	for(int i=0;i<pr1.size();++i)
		for(int j=0;j<pr2.size();++j)
		{
			if(pr1[i].hashValue==pr2[j].hashValue)
			{
				if(pr1[i].length>ans)
				{
					ans=pr1[i].length;
					str=str1.substr(pr1[i].start,pr1[i].end);
				}
			}
		}
	return str;
}
int main()
{
	string str1,str2;
	getline(cin,str1);
	getline(cin,str2);
	init(max(str1.length(),str2.length()));
	calH(H1,str1);
	calH(H2,str2);
	calSubH(H1,str1.length(),pr1);
	calSubH(H2,str2.length(),pr2);
	cout<<getMax(str1)<<endl; 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/82079067
今日推荐