求两个字符串的最长子串并输出
“ADOBE”; “ABE”;
对于这两个字符串,先标记相同字符的在矩阵中为1否则为0:
A | D | O | B | E | |
---|---|---|---|---|---|
A | 1 | 0 | 0 | 0 | 0 |
B | 0 | 0 | 0 | 1 | 0 |
E | 0 | 0 | 0 | 0 | 1 |
那么公共子串即为对角线为1的,比如‘A’、‘BE’,只需在其中找到最长的1的对角线即可,这里我们可以把对角线(i, j)表示为1+(i-1, j-1),来达到记录当前公共子串长度的目的:
A | D | O | B | E | |
---|---|---|---|---|---|
A | 1 | 0 | 0 | 0 | 0 |
B | 0 | 0 | 0 | 1 | 0 |
E | 0 | 0 | 0 | 0 | 2 |
进一步的,我们可以简化用一个1✖️5的矩阵来记录子串长度,并不断更新,注意这里要从后往前更新:
1 | 0 | 0 | 0 | 0 |
---|
0 | 0 | 0 | 1 | 0 |
---|
0 | 0 | 0 | 0 | 2 |
---|
代码如下:子串最长长度就是maxlen
//求两个字符串的最长子串并输出
#include<string>
#include<vector>
string conSubStr(string s1, string s2)//s2较短 s1较长
{
int len1 = s1.size();
int len2 = s2.size();
//储存子串长度的数组
vector<int> count(len2 + 1, 0);
//记录目前为止最长字串的长度和s2中的位置
int maxlen = 0;
int endpos = 0;
for (int i = 0; i < len1; i++)
{
for (int j = len2; j > 0; j--)
{
if (s2[j - 1] == s1[i])
{
count[j] = count[j - 1] + 1;
if (count[j] > maxlen)
{
maxlen = count[j];
endpos = j;
}
}
else
{
count[j] = 0;
}
}
}
string substr;
substr.resize(maxlen);
for (int i = endpos - maxlen; i < endpos; i++)
{
substr[i - endpos + maxlen] = s2[i];
}
return substr;
}
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
cout << conSubStr(s1, s2) << endl;
}
return 0;
}
还可以定义一个二维数组
本题需要用动态规划求解,MCS[i][j]记录短字符串 s1 前 i 个字符和长字符串 s2 前 j 个字符的最长子串的长
度,初始化所有值为 0。当 s1[i-1] = s2[j-1]时,lcs[i][j] = lcs[i - 1][j - 1] + 1,这里使用一个额外的值
start 来记录最长子串在短字符串 s1 中出现的起始位置,maxlen记录当前最长子串的长度,当lcs[i][j] >
maxlen 时,maxlen = lcs[i][j], 则start = i - maxlen ;档s1[i-1] != s2[j-1]时不需要任何操作,最后获取
substr(start, maxlen)即为所求。
#include<vector>
#include<string>
void find(string s1, string s2)//s1是较短的子串 s2是较长的子串
{
int l1 = s1.size(), l2 = s2.size(), max = 0, start = 0;
vector<vector<int>> lcs(l1 + 1, vector<int>(l2 + 1, 0));
for (int i = 1; i <= l1; i++)
{
for (int j = 1; j <= l2; j++)
{
if (s1[i - 1] == s2[j - 1])
{
lcs[i][j] = lcs[i - 1][j - 1] + 1;
}
if (lcs[i][j] > max)
{
max = lcs[i][j];
start = i - max;
}
}
}
cout << s1.substr(start, max) << endl;
}
int main()
{
string s1, s2;
while (getline(cin, s1) && getline(cin, s2))
{
if (s1.size() < s2.size())
find(s1, s2);
else
find(s2, s1);
}
return 0;
}