golang力扣leetcode 1143.最长公共子序列

简介: golang力扣leetcode 1143.最长公共子序列

1143.最长公共子序列

1143.最长公共子序列

题解

LCS

//state: dp[i][j]表示test1的前i个字符和test2的前j的字串的最长公共子序列

//function: dp[i][j]=dp[i-1][j-1]+1或者=dp[i-1][j]或者=dp[i][j-1]

//intialize:dp[0][0]=0

//answer: dp[len(text1)][len(text1)]

代码

package main
func longestCommonSubsequence(text1 string, text2 string) int {
  dp := make([][]int, len(text1)+1)
  for idx := range dp {
    dp[idx] = make([]int, len(text2)+1)
  }
  for i := 1; i <= len(text1); i++ {
    for j := 1; j <= len(text2); 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[len(text1)][len(text2)]
}
func max(a, b int) int {
  if a > b {
    return a
  }
  return b
}


目录
相关文章
|
6天前
|
Java
【LeetCode力扣】面试题 17.14. 最小K个数(top-k问题)
【LeetCode力扣】面试题 17.14. 最小K个数(top-k问题)
14 1
|
6天前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
6 0
|
6天前
|
索引
leetcode代码记录(最长公共子序列
leetcode代码记录(最长公共子序列
8 0
|
6天前
|
Go 容器 SQL
【Golang Leetcode】总目录(Day1~100)
【Golang Leetcode】总目录(Day1~100)
477 1
【Golang Leetcode】总目录(Day1~100)
|
6天前
代码随想录Day45 动态规划13 LeetCode T1143最长公共子序列 T1135 不相交的线 T53最大子数组和
代码随想录Day45 动态规划13 LeetCode T1143最长公共子序列 T1135 不相交的线 T53最大子数组和
40 0
|
6天前
|
Go
golang力扣leetcode 494.目标和
golang力扣leetcode 494.目标和
32 0
|
6天前
|
Go
golang力扣leetcode 剑指Offer II 114. 外星文字典
golang力扣leetcode 剑指Offer II 114. 外星文字典
24 0
|
6天前
|
Go
golang力扣leetcode 第 295 场周赛
golang力扣leetcode 第 295 场周赛
37 0
|
6天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
6天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
13 0

热门文章

最新文章