/*
本程序目的是用来求两字符串的最长连续子串
两字符串分别用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;
}
求两字符串的最长公共连续子串
最新推荐文章于 2022-11-03 16:10:22 发布