当前位置:网站首页>golang刷leetcode 动态规划(13) 最长公共子序列
golang刷leetcode 动态规划(13) 最长公共子序列
2022-08-02 18:53:00 【用户9710217】
给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
若这两个字符串没有公共子序列,则返回 0。
示例 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 <= 1000
1 <= text2.length <= 1000
输入的字符串只含有小写英文字符。
解题思路:
1,注意是最长公共子序列,不是最长公共子串
2,最长公共子序列问题是经典的动态规划题
3,状态转移方程
A,若str1[i]==str2[j],则str1[:i]和str2[:j]最长公共子序列的长度为
str1[:i-1]和str2[:j-1]最长公共子序列的长度加一
B, str1[:i-1]和str2[:j], str1[:i]和str2[:j-1]两者中较长者
4,未来表示方便,存储数组长度比字符串长度多1
代码实现
func longestCommonSubsequence(text1 string, text2 string) int {
h:=len(text1)+1
w:=len(text2)+1
m:=make([][]int,h)
for i:=0;i<h;i++{
m[i]=make([]int,w)
}
for i:=1;i<h;i++{
for j:=1;j<w;j++{
if text1[i-1]==text2[j-1]{
m[i][j]=m[i-1][j-1]+1
}else{
if m[i-1][j]>m[i][j-1]{
m[i][j]=m[i-1][j]
}else{
m[i][j]=m[i][j-1]
}
}
}
}
return m[h-1][w-1]
}
边栏推荐
- What skills are the most practical for college students in communications?
- Sentienl【动态数据源架构设计理念与改造实践】
- 简单有效又有用的关闭antimalware service executable的方法·备份记录
- 去年,一道蚂蚁金服笔试题,还行,中等难度
- T31开发笔记:metaipc测试
- Sentinel vs Hystrix 限流对比,到底怎么选?
- 回收站删除的文件怎么恢复,2个方法汇总助您快速解决
- 论文阅读_胶囊网络CapsNet
- 麦聪DaaS平台 3.7.0 Release 正式发布:全面支持国际化
- 线程池原理与实践|从入门到放弃,深度解析
猜你喜欢
【心理学 · 人物】第一期
From the technical panorama to the actual scene, analyze the evolutionary breakthrough of "narrowband high-definition"
Golang swagger :missing required param comment parameters
斯堪尼亚SCANIA OTL标签介绍
【C语言刷题】Leetcode238——除自身以外数组的乘积
【动态规划专项训练】基础篇
项目分析(复杂嵌入式系统设计)
I have 8 years of experience in the Ali test, and I was able to survive by relying on this understanding.
What are the useful real-time network traffic monitoring software
Functional test points for time, here is a comprehensive summary for you
随机推荐
7.22 - 每日一题 - 408
Sentinel vs Hystrix 限流对比,到底怎么选?
【C语言刷题】牛客JZ65——不用四则运算作加法
请教一个数据库连接池的问题,目前已知是事务未设置超时,又有一块代码事务没有提交,一直把连接给耗尽了,
JVM内存和垃圾回收-04.程序计数器(PC寄存器)
斯堪尼亚SCANIA OTL标签介绍
ssh configuration
Unity 打包和切换平台|Build Settings窗口介绍
想通过FC连接RDS mysql。是不是将FC服务角色添加rds权限后,就可以通过地址,端口建连了呢
7.25 - 每日一题 - 408
中国科学院院属研究单位
Electronic Industry Inventory Management Pain Points and WMS Warehouse Management System Solutions
Geoserver + mysql + openlayers problem
1.0.0到1.0.2的底层数据库表的更新,需要再重新自建数据库吗?
MySQL详细安装与配置
Monitor is easy to Mars debut: distributed operations help TOP3000 across management gap
Therapy | How to Identify and Deal with Negative Thoughts
From the technical panorama to the actual scene, analyze the evolutionary breakthrough of "narrowband high-definition"
Golang sync/atomic 包的原子操作说明
洛谷P4799 世界冰球锦标赛