题解 | 最长公共子串
注意:公共子串是要求连续的,公共子序列可以不连续
#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;
short dp[10002][10002];
int main(){
char s1[10001], s2[10001];
scanf("%s%s", s1, s2);
int m = strlen(s1);
int n = strlen(s2);
short maxcnt = 0;
for (int i = 0; i <= m; i++) {
dp[i][0] = 0;
}
for (int i = 0; i <= n; i++) {
dp[0][i] = 0;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i-1]>='a'&&s1[i-1]<='z'&&s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
maxcnt = max(maxcnt, dp[i][j]);//更新最大长度
}else{
dp[i][j] = 0;//不相等,长度归零
}
}
}
printf("%d\n",maxcnt);
return 0;
}
计算机复试机试(王道版) 文章被收录于专栏
收录王道2026年计算机复试机试的(课程)代码题解,仅供个人学习参考
查看25道真题和解析