最初写法:
dp[0][0] = s1[0]==s2[0]?1:0; for(int j = 1; j < len2; j++) { if(s1[0]==s2[j]) dp[0][j] = 1; else dp[0][j] = max(dp[0][j],dp[0][j-1]); } for(int i = 1; i < len1; i++) { if(s1[i]==s2[0]) dp[i][0] = 1; else dp[i][0] = max(dp[i][0],dp[i-1][0]); } for(int i = 1; i < len1; i++) //*********** { for(int j = 1; j < len2; j++) //*********** { if(s1[i]==s2[j]) dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = max(dp[i-1][j],dp[i][j-1]); }
int len1 = strlen(s1),len2 = strlen(s2); for(int i = 1; i <= len1; i++) //*********** { for(int j = 1; j <= len2; j++) //********* { if(s1[i-1]==s2[j-1]) dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } }
for(int i = len1-1; i >= 0; i--) //********** { for(int j = len2-1; j >= 0; j--) //********* { if(s1[i]==s2[j]) //######### dp[i][j] = dp[i+1][j+1]+1; else dp[i][j] = max(dp[i+1][j],dp[i][j+1]); } } cout<<dp[0][0]<<endl;
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <iomanip> using namespace std; #define maxn 1005 int max(int a, int b) { return a>b?a:b; } char s1[maxn],s2[maxn]; int dp[maxn][maxn]; int main(int argc, char *argv[]) { while(scanf("%s %s",s1,s2)!=EOF) { cin.get(); int len1 = strlen(s1),len2 = strlen(s2); for(int i = 0; i <= len1; i++) dp[i][0] = 0; for(int j = 0; j <= len2; j++) dp[0][j] = 0; for(int i = 1; i <= len1; i++) { for(int j = 1; j <= len2; j++) { if(s1[i-1]==s2[j-1]) //############### dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } cout<<dp[len1][len2]<<endl; } return 0; }