题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string str1;
string str2;
cin >> str1 >> str2;
if (str1.size() > str2.size()) //str1是短的字串,str2是长的字串
{
string temp = str1;
str1 = str2;
str2 = temp;
}
string comm_str; //提取出的公共字符chuan
int maxstr = 0; //最大字符串长度
for (int i = 0;i < str1.size();i++)
{
for (int j = 1;j <= str1.size() - i;j++)
{
string newstr = str1.substr(i,j);
if (str2.find(newstr) != string::npos)
{
if (newstr.size() > maxstr)
{
comm_str = newstr;
maxstr = newstr.size();
}
}
}
}
cout << comm_str;
}
// 64 位输出请用 printf("%lld")
