时间复杂度为 O ( n m ) O(nm) O(nm)( n 、 m n、m n、m分别为两个字符串的长度):
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100;
char A[N], B[N];
int dp[N][N];
int main() {
int n;
//从下标1开始读入
cin.getline(A+1, N);//gets_s(A + 1,N-1);
//cout << A + 1;
//printf("%s", A+1);
cin.getline(B + 1, N);//gets_s(B + 1,N-1);
int lenA = strlen(A + 1);//由于读入时下标从1开始,因此读取长度也从+1开始
int lenB = strlen(B + 1);
//设置边界
for (int i = 1; i <= lenA; i++) {
dp[i][0] = 0;
}
for (int j = 1; j <= lenB; j++) {
dp[0][j] = 0;
}
//状态转移方程
for (int i = 1; i <= lenA; i++) {
for (int j = 1; j <= lenB; j++) {
if (A[i] == B[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
//dp[lenA][lenB]是答案
printf("%d\n", dp[lenA][lenB]);
return 0;
}