题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <iostream>
using namespace std;
class LongestCommonSubstr {
private:
string a, b;
public:
//构造函数
LongestCommonSubstr(const string a, const string b);
//析构函数
~LongestCommonSubstr();
//最长公共子串
const string search(void)const;
//较短字符串的长度(子串最大可能长度)
const int lengthOfShorterString(void)const;
};
LongestCommonSubstr::LongestCommonSubstr(const string a, const string b) {
this->a = a;
this->b = b;
return;
}
LongestCommonSubstr::~LongestCommonSubstr() {
}
const string LongestCommonSubstr::search(void) const {
//区分出较短字串和较长字串
int len = this->lengthOfShorterString();
string shorter, longer;
if (this->a.size() == len) {
shorter = this->a;
longer = this->b;
} else {
longer = this->a;
shorter = this->b;
}
//从子串的最长可能长度开始,从较短字符串字符串的前部开始,搜寻公共子串
for (; len > 0; len--)
for (int i = 0; i <= shorter.size() - len; i++) {
string sub = shorter.substr(i, len);
for (int j = 0; j <= longer.size() - len; j++)
if (sub == longer.substr(j, len))
return sub;
}
return string();
}
const int LongestCommonSubstr::lengthOfShorterString(void) const {
int a = this->a.size();
int b = this->b.size();
return a < b ? a : b;
}
int main() {
string a, b;
while (cin >> a >> b) { // 注意 while 处理多个 case
cout << LongestCommonSubstr(a, b).search() << endl;
}
}
// 64 位输出请用 printf("%lld")
