当前位置:网站首页>【面试高频题】难度 1.5/5,LCS 模板题
【面试高频题】难度 1.5/5,LCS 模板题
2022-06-27 11:32:00 【宫水三叶的刷题日记】
题目描述
这是 LeetCode 上的 「1143. 最长公共子序列」 ,难度为 「中等」。
Tag : 「最长公共子序列」、「LCS」、「序列 DP」
给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
例如, "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 。
提示:
text1和text2仅由小写英文字符组成。
动态规划(空格技巧)
这是一道「最长公共子序列(LCS)」的裸题。
对于这类题的都使用如下「状态定义」即可:
代表考虑 的前 个字符、考虑 的前 的字符,形成的最长公共子序列长度。
当有了「状态定义」之后,基本上「转移方程」就是呼之欲出:
s1[i]==s2[j]: 。代表 「必然使用 与 时」 LCS 的长度。s1[i]!=s2[j]: 。代表 「必然不使用 (但可能使用)时」 和 「必然不使用 (但可能使用)时」 LCS 的长度。
一些编码细节:
通常我会习惯性往字符串头部追加一个空格,以减少边界判断(使下标从 1 开始,并很容易构造出可滚动的「有效值」)。
Java 代码:
class Solution {
public int longestCommonSubsequence(String s1, String s2) {
int n = s1.length(), m = s2.length();
s1 = " " + s1; s2 = " " + s2;
char[] cs1 = s1.toCharArray(), cs2 = s2.toCharArray();
int[][] f = new int[n + 1][m + 1];
// 因为有了追加的空格,我们有了显然的初始化值(以下两种初始化方式均可)
// for (int i = 0; i <= n; i++) Arrays.fill(f[i], 1);
for (int i = 0; i <= n; i++) f[i][0] = 1;
for (int j = 0; j <= m; j++) f[0][j] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (cs1[i] == cs2[j]) {
f[i][j] = f[i -1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
// 减去最开始追加的空格
return f[n][m] - 1;
}
}
C++ 代码:
class Solution {
public:
int longestCommonSubsequence(string s1, string s2) {
int n = s1.size(), m = s2.size();
s1 = " " + s1, s2 = " " + s2;
int f[n+1][m+1];
memset(f, 0, sizeof(f));
for(int i = 0; i <= n; i++) f[i][0] = 1;
for(int j = 0; j <= m; j++) f[0][j] = 1;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(s1[i] == s2[j]) {
f[i][j] = max(f[i-1][j-1] + 1, max(f[i-1][j], f[i][j-1]));
} else {
f[i][j] = max(f[i-1][j], f[i][j-1]);
}
}
}
return f[n][m] - 1;
}
};
时间复杂度: 空间复杂度:
动态规划(利用偏移)
上述「追加空格」的做法是我比较习惯的做法
事实上,我们也可以通过修改「状态定义」来实现递推:
代表考虑 的前 个字符、考虑 的前 的字符,形成的最长公共子序列长度。
那么最终的 就是我们的答案, 当做无效值,不处理即可。
s1[i-1]==s2[j-1]: 。代表使用 与 形成最长公共子序列的长度。s1[i-1]!=s2[j-1]: 。代表不使用 形成最长公共子序列的长度、不使用 形成最长公共子序列的长度。这两种情况中的最大值。
Java 代码:
class Solution {
public int longestCommonSubsequence(String s1, String s2) {
int n = s1.length(), m = s2.length();
char[] cs1 = s1.toCharArray(), cs2 = s2.toCharArray();
int[][] f = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (cs1[i - 1] == cs2[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
return f[n][m];
}
}
Python3 代码:
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j],dp[i][j - 1])
return dp[m][n]
C++ 代码:
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size(), n = text2.size();
vector<vector<int>> dp(m + 1,vector<int>(n + 1,0));
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(text1[i - 1] == text2[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else{
dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};
Golang 代码:
func longestCommonSubsequence(text1 string, text2 string) int {
m := len(text1)
n := len(text2)
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if text1[i] == text2[j] {
dp[i+1][j+1] = dp[i][j] + 1
} else {
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
}
}
}
return dp[m][n]
}
func max(i int, j int) int {
if i > j {
return i
}
return j
}
时间复杂度: 空间复杂度:
最后
这是我们「刷穿 LeetCode」系列文章的第 No.1143 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。
更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地
边栏推荐
- Online bidding of Oracle project management system
- Codeforces Round #786 (Div. 3) ABCDE
- "24 of the 29 students in the class successfully went to graduate school" rushed to the hot search! Where are the remaining five?
- R language uses the poisgof function of epidisplay package to test the goodness of fit of Poisson regression and whether there is overdispersion
- Microsoft cloud technology overview
- Jwas: a Bayesian based GWAS and GS software developed by Julia
- 【TcaplusDB知识库】TcaplusDB-tcapsvrmgr工具介绍(一)
- R语言使用glm函数构建泊松对数线性回归模型处理三维列联表数据构建饱和模型、使用step函数基于AIC指标实现逐步回归筛选最佳模型、解读分析模型
- Leetcode 729. My schedule I (awesome, solved)
- How to adjust an integer that is entered in Excel but always displays decimals?
猜你喜欢

Matlab exercises - create 50 rows and 50 columns of all zero matrix, all 1 matrix, identity matrix, diagonal matrix, and output the 135 element of the matrix.
![[tcapulusdb knowledge base] Introduction to tcapulusdb tcapsvrmgr tool (I)](/img/04/b1194ca3340b23a4fb2091d1b2a44d.png)
[tcapulusdb knowledge base] Introduction to tcapulusdb tcapsvrmgr tool (I)
![Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]](/img/d1/5beed6c86c4fdc024c6c9c66fbffb8.png)
Jerry's serial port communication serial port receiving IO needs to set digital function [chapter]

Jwas: a Bayesian based GWAS and GS software developed by Julia

Unity Shader学习(一)认识unity shader基本结构

2022CISCN华中 Web

JSP自定义标签

15+城市道路要素分割应用,用这一个分割模型就够了!

【TcaplusDB知识库】TcaplusDB单据受理-事务执行介绍

L'utilisation de C language 0 length Array
随机推荐
从零开始搭建物联网系统
21: Chapter 3: develop pass service: 4: further improve [send SMS, interface]; (in [send SMS, interface], call Alibaba cloud SMS service and redis service; a design idea: basecontroller;)
R语言使用MASS包的polr函数构建有序多分类logistic回归模型、使用VGAM包的vglm函数对有序多分类logistic回归模型进行平行性假设作检验
Usage of rxjs mergemap
Drive to APasS! Use Mingdao cloud to manage F1 events
建木持续集成平台v2.5.0发布
Wait, how do I use setmemorylimit?
【TcaplusDB知识库】TcaplusDB单据受理-建表审批介绍
"24 of the 29 students in the class successfully went to graduate school" rushed to the hot search! Where are the remaining five?
【TcaplusDB知识库】Tmonitor系统升级介绍
【TcaplusDB知识库】TcaplusDB数据导入介绍
R语言glm函数构建二分类logistic回归模型(family参数为binomial)、使用AIC函数比较两个模型的AIC值的差异(简单模型和复杂模型)
C# wpf 实现撤销重做功能
MapReduce原理剖析(深入源码)
Jerry's seamless looping [chapter]
0基础了解电商系统如何对接支付渠道
旭日3SDB,安装原版ros
[tcapulusdb knowledge base] Introduction to tcapulusdb general documents
【TcaplusDB知识库】TcaplusDB-tcaplusadmin工具介绍
JSP自定义标签