题目
- 最长公共子序列
题目描述
给定两个字符串 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。
思路
求最值的问题,都会想到动态规划问题,这里我们直接找动态规划的三要素
Dp tabel含义:对于dp[i][j]的含义,对于text1[0...i-1]和text2[0...j-1]最长公共子序列是dp[i][j]
base case: 索引为0列和行表示空串,即dp[...][0]和dp[0][...]都表示0
状态转移方程:
if text1[i] == text2[j] {
dp[i][j] = dp[i-1, j-1] + 1
}
if text1[i] != text2[j] {
dp[i][j] = max(dp[i-1, j], dp[i, j-1])
}
代码
package leetcode
import(
"log"
)
// longestCommonSubsequence
// 1143. 最长公共子序列
func longestCommonSubsequence(text1 string, text2 string) int {
w := len(text1)
h := len(text2)
// base case
// 初始化
dp := MakeIntSlice(w+1, h+1)
log.Println(dp)
for i:=1; i<=w; i++ {
for j:=1; j<=h; 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[w][h]
}
func max(a, b int) int{
if a > b {
return a
}
return b
}
// MakeSlice
// 创建二维切片
func MakeIntSlice(row, column int) [][]int {
data := make([][]int, row)
for index := range data {
data[index] = make([]int, column)
}
return data
}
参考
来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/lo…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。