LeetCode算法日记 - Day 101: 最长公共子序列
目录
1. 最长公共子序列
1.1 题目解析
1.2 解法
1.3 代码实现
1. 最长公共子序列
https://leetcode.cn/problems/longest-common-subsequence/description/
给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
- 例如,
"ace"是"abcde"的子序列,但"aec"不是"abcde"的子序列。
两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。
示例 1:
输入:text1 = "abcde", text2 = "ace" 输出:3 解释:最长公共子序列是 "ace" ,它的长度为 3 。
示例 2:
输入:text1 = "abc", text2 = "abc" 输出:3 解释:最长公共子序列是 "abc" ,它的长度为 3 。
示例 3:
输入:text1 = "abc", text2 = "def" 输出:0 解释:两个字符串没有公共子序列,返回 0 。
提示:
1 <= text1.length, text2.length <= 1000text1和text2仅由小写英文字符组成。
1.1 题目解析
题目本质
在 text1 和 text2 中找到最长的公共序列长度,本质是子问题最优模型。
常规解法
枚举 text1 的所有子序列,再在 text2 中检查是否存在,取最长。
class Solution {public int longestCommonSubsequence(String text1, String text2) {int n = text1.length();int res = 0;for (int mask = 1; mask < (1 << n); mask++) {StringBuilder sb = new StringBuilder();for (int i = 0; i < n; i++) {if ((mask & (1 << i)) != 0) {sb.append(text1.charAt(i));}}if (isSubsequence(sb.toString(), text2)) {res = Math.max(res, sb.length());}}return res;}private boolean isSubsequence(String sub, String target) {int i = 0;for (int j = 0; j < target.length() && i < sub.length(); j++) {if (target.charAt(j) == sub.charAt(i)) {i++;}}return i == sub.length();}}
问题分析
枚举所有子序列需要 O(2^n),再配合检查,远超题目规模上限。
思路转折
观察子问题的重叠性和最优子结构,若能复用即可降到多项式时间 ⇒ 用二维动态规划记录 prefix(i,j) 的最优值。
1.2 解法
算法思想
定义 dp[i][j] 为 text1 前 i 个字符与 text2 前 j 个字符的最长公共子序列长度。若末尾字符相等,则继承 dp[i-1][j-1]+1;否则取 dp[i-1][j] 与 dp[i][j-1] 的最大值。
步骤拆解
i)转为字符数组备查。
ii)初始化 (n+1) × (m+1) 的 dp,第 0 行/列为 0。
iii)双层循环填表:比较末尾字符,依递推式更新。
iv)返回 dp[n][m]。
易错点
-
循环下标对应 dp 时一律用 i-1、j-1 访问字符,避免越界。
-
dp 需多一行一列存放空前缀,初始化为 0。
-
若字符不同,取 dp[i-1][j] 与 dp[i][j-1] 的最大值。
1.3 代码实现
class Solution {public int longestCommonSubsequence(String text1, String text2) {char[] ch1 = text1.toCharArray();char[] ch2 = text2.toCharArray();int n = ch1.length;int m = ch2.length;int[][] dp = new int[n + 1][m + 1];for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; 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]);}}}return dp[n][m];}
}
复杂度分析
-
时间复杂度: O(n × m)
-
空间复杂度: O(n × m)
