当前位置:网站首页>1143.最长公共子序列
1143.最长公共子序列
2022-07-15 14:31:00 【zzu菜】
1143.最长公共子序列
给定两个字符串 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 。
思考
定义dp数组及其下标含义
dp[i][j]:表示nums1中前i个数和nums2中前j个数公共的 、长度最长的子数组的长度 。
状态转移方程
nums1[i-1] = nums2[j-1]时,dp[i][j] = dp[i-1][j-1] + 1
否则等于 dp[i][j] = Math.max( dp[i-1][j-1], dp[i-1][j], dp[i][j-1] )
就是和718. 最长重复子数组 差异在这里 因为这里不要求连续
初始化dp数组
第一行和第一列进行初始化
初始化第一列,在找到text1[i] ==text2[0]之前dp[i][0]均设置为 0 ,找到后dp[i][0]设为1。
初始化第一行省略。
package 力扣;
/** * @author yyq * @create 2022-07-14 16:02 */
public class leetcode1143 {
public int longestCommonSubsequence(String text1, String text2) {
// 创建Dp数组
int[][] dp = new int[text1.length()][text2.length()];
// 初始化Dp数组
int flag = 1;
for (int i = 0;i<text1.length();i++){
if (flag==0||text1.charAt(i)==text2.charAt(0)){
flag = 0;
dp[i][0] = 1;
}
}
flag = 1;
for (int j = 0;j<text2.length();j++){
if (flag==0||text1.charAt(0)==text2.charAt(j)){
flag = 0;
dp[0][j] = 1;
}
}
// 完善dp数组
for (int i = 1;i<text1.length();i++){
for (int j=1;j<text2.length();j++){
if(text1.charAt(i) == text2.charAt(j)){
dp[i][j] = dp[i-1][j-1] + 1 ;
}else {
int max = Math.max(dp[i][j-1],dp[i-1][j]);
max = Math.max(max,dp[i-1][j-1]);
dp[i][j] = max;
}
}
}
for (int i = 0;i<text1.length();i++){
for (int j=0;j<text2.length();j++){
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
return dp[text1.length()-1][text2.length()-1];
}
}
边栏推荐
- 【c语言】高精度加减乘除模板
- 剑指Offer17-打印从1到最大的n位数-模拟
- 腾讯云EKS 上部署 eshopondapr
- PAT 甲级 A 1099 Build A Binary Search Tree
- GPU distributed training
- Notes tree traversal
- Quickly deploy mqtt clusters on Alibaba cloud using terraform
- Properties and traversal of binary trees
- 巴比特 | 元宇宙每日必读:腾讯新闻暂停数字藏品的售卖服务,用户留言要求“退款”,幻核也陷入“滞销”困境,这释放了什么信息?...
- 1301_两种方式为开发板增加串口监控功能
猜你喜欢
随机推荐
开源数据质量解决方案——Apache Griffin入门宝典
Pat grade a a1094 the largest generation
GPU — 分布式训练
程序运行问题排查和解决:an instance of ‘std::logic_error‘what(): basic_string::_M_construct null not valid
scrollIntoView实现简单的锚点定位(示例:选择城市列表)
MySQL 字符串函数
如何定制.NET6.0的日志记录
Machine learning exercise 4 - neural networks
dnssec-verification-with-dig【使用dig验证dnssec】
手机开通华泰券商账户安全吗?
OKX 金融市场总监 Lennix Lai:Web3 是一场革命
Pat grade a A1020 tree Traversals
Pat grade a 1090 highest price in supply chain
PAT 甲级 A1064 Complete Binary Search Tree
GPU distributed training
高性能算力中心 — RDMA — NVIDIA SHARP
工业交换机的单模和多模能否互相替代?
Daily question brushing record (24)
二叉树的性质和遍历
C语言基础知识(自用)








