class Solution {
public int longestCommonSubsequence(String text1, String text2) {
/**
1.确定dp数组 dp[i][j] 以i-1为结尾的text1和以j-1为结尾的text2拥有的公共子序列的长度
*/
char[] ch1 = text1.toCharArray();
char[] ch2 = text2.toCharArray();
int n1 = text1.length();
int n2 = text2.length();
int[][] dp = new int[n1+1][n2+1];
// 2.确定递推关系
/**
if(ch1[i-1] == ch2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
// 如果两个不相等 将其中一个后退一格取最大值
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
*/
int result = 0;
// 3.初始化
// 4.遍历顺序
for(int i=1; i<=n1; i++){
for(int j=1; j<=n2; 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-1][j],dp[i][j-1]);
}
result = Math.max(result,dp[i][j]);
}
}
return result;
}
}
运行结果: