题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
// HJ65-2 查找两个字符串a,b中的最长公共子串.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
int max = 0,ans=0; string res = "",tmp="";
if (s1.size() > s2.size())
{
string bmp = s1;
s1 = s2;
s2 = bmp;
}
int len1 = s1.size();
for (int i = 0; i < len1; i++)
{
for (int j = i; j < len1; j++)
{
for (int k = 0; k < s2.size(); k++)
{
tmp = s1.substr(i, j - i + 1);
if (tmp.compare(s2.substr(k, tmp.size())) == 0)
{
ans = tmp.size();
if (ans > max)
{
max = ans;
res = tmp;
}
}
}
}
}
cout << res << endl;
}
return 0;
}
