前言
题目: HJ75 公共子串计算
编程语言: C++
解题状态: 艰难完成
思路
暴力解法,要注意的是遍历的范围,以及如何求取连续子串的长度。
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string a, b;
cin >> a;
cin >> b;
string longStr, shortStr;
if (a.size() >= b.size()) {
longStr = a;
shortStr = b;
} else {
longStr = b;
shortStr = a;
}
int length = 0;
for (int i = 0; i < longStr.size(); i++) {
int curMaxLen = 0;
int curLen = 0;
for (int j = 0; j < shortStr.size() && i + j < longStr.size(); j++) {
if (longStr[i + j] == shortStr[j]) {
curLen++;
} else {
curLen = 0;
}
curMaxLen = curLen > curMaxLen ? curLen : curMaxLen;
}
length = curMaxLen > length ? curMaxLen : length;
}
for (int i = 0; i < shortStr.size(); i++) {
int curMaxLen = 0;
int curLen = 0;
for (int j = 0; j < longStr.size() && i + j < shortStr.size(); j++) {
if (shortStr[i + j] == longStr[j]) {
curLen++;
} else {
curLen = 0;
}
curMaxLen = curLen > curMaxLen ? curLen : curMaxLen;
}
length = curMaxLen > length ? curMaxLen : length;
}
cout << length << endl;
return 0;
}
标签:子串,int,longStr,curMaxLen,HJ75,curLen,NowCoder,shortStr,size
From: https://blog.csdn.net/daishabby2486/article/details/141901924