1- 思路
题目识别
- 识别1 :两个数组的最长公共子序列,返回的是
最长公共子序列的长度
动规五部曲
- 1- 定义 dp 数组
dp[i][j]
代表,长度为 i-1
的 nums1
和长度为 j-1
的 nums2
的长度
- 2- 递推公式
- 如果两个字符相同了
dp[i][j] = dp[i-1][j-1] +1
- 否则:
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1])
- 3- 初始化
- 4- 递推
- 由于
[i][j]
根据 [i-1][j-1]
来,所以从上到下,从左到右遍历
2- 实现
⭐5. 最长回文子串——题解思路

class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1+1][len2+1];
for(int i = 1 ; i <= len1;i++){
for(int j = 1 ; j <= len2;j++){
if(text1.charAt(i-1) == text2.charAt(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]);
}
}
}
return dp[len1][len2];
}
}
3- ACM 实现
public class longestCommon {
public static int longestCommon(String text1,String text2){
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1+1][len2+1];
for(int i = 1 ; i <= len1;i++){
for(int j = 1 ; j <= len2;j++){
if(text1.charAt(i-1) == text2.charAt(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]);
}
}
}
return dp[len1][len2];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text1 = sc.nextLine();
String text2 = sc.nextLine();
System.out.println("结果是"+longestCommon(text1,text2));
}
}