题目:
今天这题也是动态规划的经典题目了。难得直接手撕了一次。
要点:
1.处理公共最长子序列的时候,一般都会计算上空字符串,因此动态规划的二维数组需要多申请一位。
2.用ans【i】【j】表示text1【0…i】和text2【0…j】的最长公共子串
3.ans【i】【j】有两种情况:
当前字符相等时,ans【i】【j】等于text1和text2各减少一位的最长公共子串长度+1
当前字符不相等时,等于text1或者text2减少一位的最大值。
C++代码附带测试:
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.length()+1;
int n = text2.length()+1;
int ans[m][n];
for(int i=0;i<n;i++){
ans[0][i] = 0;
}
for(int i=0;i<m;i++){
ans[i][0] = 0;
}
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
if(text1[i-1]==text2[j-1]){//这里要-1,因为加了空字符串
ans[i][j] = ans[i-1][j-1]+1;
}else{
ans[i][j] = max(ans[i-1][j],ans[i][j-1]);
}
}
}
return ans[m-1][n-1];
}
};
int main(){
string text1 = "abc";
string text2 = "def";
Solution solution;
cout<<solution.longestCommonSubsequence(text1,text2)<<endl;
}