思路:dp[i][j]的含義爲str1[0..i]與str2[0..j]的最長公共子序列長度.ios
#include<iostream> #include<string> using namespace std; const int maxn = 100; int main() { string str1,str2; cin>>str1; cin>>str2; int dp[maxn][maxn]; for(int i = 0; i < str1.length(); i++) { if(dp[i - 1][0] == 1) { dp[i][0] = 1; continue; } if(str1[i] == str2[0]) { dp[i][0] = 1; } else dp[i][0] = 0; } for(int j = 0; j < str2.length(); j++) { if(dp[0][j -1] == 1) { dp[0][j] = 1; continue; } if(str1[0] == str2[j]) { dp[0][j] = 1; } else dp[0][j] = 0; } for(int i = 1; i < str1.length(); i++) { for(int j = 1; j < str2.length(); j++) { if(str1[i] == str2[j]) dp[i][j] = max(max(dp[i -1][j],dp[i][j - 1]),dp[i-1][j-1]+1); else dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]); } } cout<<dp[str1.length() - 1][str2.length() - 1]<<endl; return 0; }