状态转移方程:
if(ch1i - 1 == ch2j - 1){
dpij = dpi - 1j - 1 + 1;
}else{
dpij = Math.max(dpij-1,dpi-1j);
}
dp数组的含义:表示长度为i-1和j-1的两个字符串的最长公共子序列;
java
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
char[] ch1 = text1.toCharArray();
char[] ch2 = text2.toCharArray();
int[][] dp = new int[ch1.length + 1][ch2.length + 1];
for(int i = 0;i < dp.length;i++){
for(int j = 0;j < dp[0].length;j++){
if(i == 0 || j == 0){
dp[i][j] = 0;
}
}
}
for(int i = 1;i < dp.length;i++){
for(int j = 1;j < dp[0].length;j++){
if(ch1[i - 1] == ch2[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else{
dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]);
}
}
}
return dp[ch1.length][ch2.length];
}
}