求两字符串的最长公共连续子串

/*
本程序目的是用来求两字符串的最长连续子串
两字符串分别用str1={str1[1],...,str1[m]}和str2={str2[1],str2[1],...,str2[n]}表示
思路:
    首先比较str1[m]和str2[n]
	1、如果str1[m] != str2[n],那么最长连续子串,要么是{str1[1],...,str1[m-1]}和{str2[1],...,str2[n]}
		的最长公共连续子串;要么是{str1[1],...,str1[m]}和{str2[1],...,str2[n - 1]}的最长公共连续子串
	2、如果str1[m] == str2[n],那么str1和str2的最长公共连续子串可能是包括str1[m] == str2[n]这个字符的字符;
	要么不包括这个字符,也就是说他们的最长连续子串是{str1[1],...,str1[m-1]}和{str2[1],...,str2[n-1]}的
	最长公共子串。

	我们用一个二维数组vec来存储最长连续子串的长度,并且vec[i][j]表示字符串str1[1,...,i]和str2[1,...,j]以
	str1[i]和str2[j]结尾的最长连续子串的长度。
		也就是说,如果str1[i] != str2[j],那么vec[i][j] = 0。
		否则,str1[i] == str2[j], vec[i][j] = vec[i - 1][j - 1] + 1;
		vec[i][j] = 0,当i == 0 或者 j == 0时。

	最后我们找出vec数组中最大的值,就可以求出最长公共连续子串了。
*/
#include<iostream>
#include<string>
#include<vector>
using namespace std;

//find_largest_substring用来查找str1和str2中最大的连续子串
//如果找到返回true,并将子串存储在substr中。否则返回false

bool find_largest_substring(const string& str1, const string& str2, string& substr)
{
	if(str1.empty() || str2.empty())
		return false;
	size_t len1 = str1.size();
	size_t len2 = str2.size();
	
	vector<vector<int> > vec(len1 + 1, vector<int>(len2 + 1, 0));
	for(size_t row = 1; row != len1 + 1; row++) {
		for(size_t col = 1; col != len2 + 1; col++) {
			if(str1[row - 1] == str2[col - 1]) {
				vec[row][col] = vec[row - 1][col - 1] + 1;
			}
			else { //str1[row - 1] != str2[col - 1]
				vec[row][col] = 0;
			}
		}
	}

	int max = 0;
	int x = 0, y = 0;
	//找出长度最长的值
	for(size_t row = 1; row != len1 + 1; row++) {
		for(size_t col = 1; col != len2 + 1; col++) {
			if(vec[row][col] > max) {
				max = vec[row][col];
				x = row;
				y = col;
			}
		}
	}
	
	string ss(str1, x - max,max);
	substr = ss;
	return true;
}

int main(void)
{
	string str1, str2;
	string substr;
	cin >> str1 >> str2;
	bool result;
	result = find_largest_substring(str1, str2, substr);
	if(result)
		cout << substr << endl;
	else
		cout << "not find !" << endl;
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值