LeetCode 1143. 最长公共子序列

题目描述

1143. 最长公共子序列

image-20220921002108483

思路分析

🔄dp[i][j]表示text1[0:i]text2[0:j]最长公共子序列的长度

image-20250510085945359

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func longestCommonSubsequence(text1 string, text2 string) int {
	m, n := len(text1), len(text2)

	var dp = make([][]int, m+1)
	for i := range dp {
		dp[i] = make([]int, n+1)
	}

	for i := 1; i <= m; i++ {
		for j := 1; j <= n; 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[m][n]
}
  • 时间复杂度:O (m * n),其中 m 和 n 分别是 text1text2 的长度。
  • 空间复杂度:O (m * n),用于存储动态规划数组 dp

➡️ 点击查看 Java 题解

1
write your code here

相似题目

image-20250510090212795

本文作者:
本文链接: https://hgnulb.github.io/blog/2025/40931089
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!