求两个字符串最大公共子字符串长度并输出:
1.常用方法:
代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "string"
#include "algorithm"
using namespace std;
int commonStrlen(string s1, string s2)
{
if (s1.empty()||s2.empty())
{
return 0;
}
int len1 = s1.size();
int len2 = s2.size();
int res = 0;
int endpos = 0;
for (int i = 0; i < len1;++i)
{
for (int j = 0; j < len2;++j)
{
int m = i;
int n = j;
int len = 0; //每次置0更新
while (s1[m] == s2[n] && m < len1 && n < len2)
{
len++;
if (len>res)
{
endpos = m; //记录最长子字符串的末尾
}
m++;
n++;
}
res = max(res, len);
}
}
cout << "最长公共子字符串:" << endl;
for (int k = res; k > 0;k--)
{
cout << s1[endpos-res+1];
endpos++;
}
cout << endl;
return res;
}
int main()
{
string str1 = "hello";
string str2 = "helloo world";
int i = commonStrlen(str1, str2);
cout<<"最长公共子字符串长度:"<<i<<endl;
system("pause");
return 0;
}
2.二维矩阵方法:
1、把两个字符串分别以行和列组成一个二维矩阵{默认为0}。
2、比较二维矩阵中每个点对应行列字符中否相等,相等的话值设置为1,否则设置为0。
3、通过查找出值为1的最长对角线就能找到最长公共子串。
两个字符串有两个公共子字符串,最长的公共子字符串为5;
如果字符串比较长的话这样靠自己来数长度的话会很麻烦,所以我们将二维矩阵元素的值由Array[i][j]=1转换为为Array[i][j]=1 +Array[i-1][j-1],这样就避免了后续查找对角线长度的麻烦操作,代码中只要用一个maxlength变量记录最大值就可以了。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "algorithm"
using namespace std;
int commonStrlen(string s1, string s2)
{
if (s1.empty() || s2.empty())
{
return 0;
}
int len1 = s1.length();
int len2 = s2.length();
int maxlength = 0;
int Array[256][256] = { 0 };
for (int i = 0; i < len1; i++)
{
for (int j = 0; j < len2; j++)
{
if (s1[i] == s2[j])
{
if (i > 0 && j > 0)
{
Array[i][j] = Array[i - 1][j - 1] + 1;
}
else
{
Array[i][j] = 1;
}
maxlength = max(maxlength, Array[i][j]);
}
else
{
Array[i][j] = 0;
}
}
}
for (int i = 0; i < len1; ++i)
{
for (int j = 0; j < len2; ++j)
{
cout << Array[i][j] << " ";
}
cout << endl;
}
return maxlength;
}
int main()
{
string str1 = "abcdzxcabcdef";
string str2 = "abcdefg";
int res = commonStrlen(str1, str2);
cout << "最大公共子串长度是:" << endl;
cout << res << endl;
system("pause");
return 0;
}