当前位置:网站首页>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]
}边栏推荐
- 备战无人机配送:互联网派To C、技术派To B
- js Fetch返回数据res.json()报错问题
- 「日志」深度学习 CUDA环境配置
- Detailed explanation of common examples of dynamic programming
- E. Add Modulo 10(规律)
- From the technical panorama to the actual scene, analyze the evolutionary breakthrough of "narrowband high-definition"
- 汇编实例解析--利用tcb,tss,全局tss,ldt管理任务实现任务切换
- 竞赛:糖尿病遗传风险检测挑战赛(科大讯飞)
- T31开发笔记:metaipc测试
- 流量分析第二题
猜你喜欢
随机推荐
[Dynamic Programming Special Training] Basics
SQL Alias Aliases
Mobile Banking Experience Test: How to Get the Real User Experience
药品研发--检验记录与检验报告书的书写细则
流量分析第一题
药品研发--工艺技术人员积分和职务考核评估管理办法
NC | Structure and function of soil microbiome reveal N2O release from global wetlands
Functional test points for time, here is a comprehensive summary for you
JVM内存和垃圾回收-04.程序计数器(PC寄存器)
简单有效又有用的关闭antimalware service executable的方法·备份记录
【C语言刷题】双指针原地修改数组(力扣原题分析)
基于OpenGL的冰川与火鸟(光照计算模型、视景体、粒子系统)
日常开发中,String类中常用的方法
I have 8 years of experience in the Ali test, and I was able to survive by relying on this understanding.
MySQL 事件调度
Mppt光伏最大功率点跟踪控制matlab仿真
Electronic Industry Inventory Management Pain Points and WMS Warehouse Management System Solutions
Sentinel vs Hystrix 限流对比,到底怎么选?
洛谷P2574 XOR的艺术
荐号 | 当一个人不联系你,不拉黑你,原因只有一个……!







