1143. 最长公共子序列
动态规划
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
/**
* dp[i][j]定义为text1[i - 1] == text2[j - 1]时的公共子序列的最大长度
*/
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
for (int i = 1; i < text1.length() + 1; i++) {
for (int j = 1; j < text2.length() + 1; j++) {
/**
* 如果找到了重复的字符,等于该字符前面的最长公共长度加1
* 如果不相等,就取两个字符串各往前一步的最大值
*/
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]);
}
}
}
/**
* 每个位置的dp[i][j]都会继承前面的值,因此最大值肯定在最后一位,不用每次循环都记录最大值
*/
return dp[text1.length()][text2.length()];
}
}
/**
* 时间复杂度 O(n^2)
* 空间复杂度 O(n^2)
*/
https://leetcode-cn.com/problems/longest-common-subsequence/

浙公网安备 33010602011771号