题解 | #公共子串计算#
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
#include <iostream>
#include <string>
using namespace std;
//公共子串计算
class ComSubstrCalc {
private:
string s1, s2;
private:
//两个字符串较短者的长度(公共子串最大可能长度)
const int lengthOfTheShorter(void)const;
public:
//构造函数
ComSubstrCalc(const string s1, const string s2);
//析构函数
~ComSubstrCalc();
//最大公共子串的长度
const int LenOfMaxComSubstr(void)const;
};
ComSubstrCalc::ComSubstrCalc(const string s1, const string s2) {
this->s1 = s1;
this->s2 = s2;
return;
}
ComSubstrCalc::~ComSubstrCalc() {
}
const int ComSubstrCalc::lengthOfTheShorter(void) const {
int a = this->s1.size();
int b = this->s2.size();
return a < b ? a : b;
}
const int ComSubstrCalc::LenOfMaxComSubstr(void) const {
int len = this->lengthOfTheShorter();
//从最大可能长度开始,找到公共子串即返回
for (; len > 0; len--)
for (int i = 0; i <= this->s1.size() - len; i++) {
string s = this->s1.substr(i, len);
for (int j = 0; j <= this->s2.size() - len; j++)
if (s == this->s2.substr(j, len))
return len;
}
return 0;
}
int main() {
string a, b;
while (cin >> a >> b) { // 注意 while 处理多个 case
cout << ComSubstrCalc(a, b).LenOfMaxComSubstr() << endl;
}
}
// 64 位输出请用 printf("%lld")


查看19道真题和解析