题解 | 公共子串计算
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
#include <iostream> #include <string> using namespace std; #define N 200 int dp[2][N]; int getLongestCommonSubString(string& a, string& b) { int lena = a.size() - 1; int lenb = b.size() - 1; int maxlen = 0; for (int i = 1; i <= lena; ++i) { for (int j = 1; j <= lenb; ++j) { if (a[i] == b[j]) { dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1; if (maxlen < dp[i % 2][j]) maxlen = dp[i % 2][j]; } else { dp[i % 2][j] = 0; // 清零,防止错误数据积累 } } } return maxlen; } int main() { string s1; string s2; cin >> s1 >> s2; s1 = " " + s1; s2 = " " + s2; cout << getLongestCommonSubString(s1, s2) << endl; return 0; }