当前位置:网站首页>输入两个字符串,输出最长相同子串

输入两个字符串,输出最长相同子串

2022-06-22 17:50:00 Douglas_LT

#pragma warning(disable :4996)
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include <stdio.h>
#include<string> 
#include<vector>
#include<algorithm>
#include<map>
using namespace std;

typedef long long LL;
const LL MOD = 1000000007;
const LL P = 1000009;
const LL MAXN = 1010;
LL powP[MAXN] = {
     0 }, H1[MAXN] = {
     0 }, H2[MAXN] = {
     0 };

vector<pair<int, pair<int, int>>>  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 = 0; i < str.length(); i++)
	{
    
		H[i] = (H[i - 1] * P + str[i]) % MOD;
	}
}

LL calSingleSubH(LL H[],int i,int j)
{
    
	if (i == 0)
	{
    
		return H[j];
	}
	else
	{
    
		return abs(H[j] - H[i - 1] * powP[j - i + 1]) % MOD;
	}
}

void calSubH(LL H[], int len,vector<pair<int, pair<int, int>>>& pr)
{
    
	for (int i = 0; i < len; i++)
	{
    
		for (int j = 1; j < len; j++)
		{
    
			int hashvalue = calSingleSubH(H, i, j);
			pr.push_back(make_pair(hashvalue,make_pair(i,j)));
		}
	}
}

int beginn=0, endd=0;
void getmax()
{
    
	pair<int, int>p;
	int ans = 0;
	for (int i = 0; i < pr1.size(); i++)
	{
    
		for (int j = 0; j < pr2.size(); j++)
		{
    
			if (pr1[i].first == pr2[j].first)
			{
    
				p=pr1[i].second;
				int temp1 = p.first,temp2=p.second;
				if (temp2 - temp1 > ans)
				{
    
					ans = temp2 - temp1;
					beginn = temp1;
					endd = temp2;
				}
			}
		}
	}
}

int main()
{
    
	string s1, s2;
	cin >> s1 >> s2;
	int len1 = s1.length(), len2 = s2.length();
	init(max(len1, len2));
	calH(H1, s1);
	calH(H2, s2);
	calSubH(H1, len1, pr1);
	calSubH(H2, len2, pr2);
	getmax();
	for (int i = beginn; i <= endd; i++)
	{
    
		cout << s1[i];
	}
	
	return 0;
}

原网站

版权声明
本文为[Douglas_LT]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Douglas_LT/article/details/109861702