Skip to content

Commit ba2209e

Browse files
Create 1143. 最长公共子序列.md
1 parent 3edd827 commit ba2209e

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#### 1143. 最长公共子序列
2+
3+
难度:中等
4+
5+
---
6+
7+
给定两个字符串 `text1` 和 `text2`,返回这两个字符串的最长 **公共子序列** 的长度。如果不存在 **公共子序列** ,返回 `0`
8+
9+
一个字符串的  **子序列**  是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
10+
11+
* 例如,`"ace"``"abcde"` 的子序列,但 `"aec"` 不是 `"abcde"` 的子序列。
12+
13+
两个字符串的 **公共子序列** 是这两个字符串所共同拥有的子序列。
14+
15+
**示例 1:**
16+
17+
```
18+
输入:text1 = "abcde", text2 = "ace"
19+
输出:3
20+
解释:最长公共子序列是 "ace" ,它的长度为 3 。
21+
```
22+
23+
**示例 2:**
24+
25+
```
26+
输入:text1 = "abc", text2 = "abc"
27+
输出:3
28+
解释:最长公共子序列是 "abc" ,它的长度为 3 。
29+
```
30+
31+
**示例 3:**
32+
33+
```
34+
输入:text1 = "abc", text2 = "def"
35+
输出:0
36+
解释:两个字符串没有公共子序列,返回 0 。
37+
```
38+
39+
**提示:**
40+
41+
* `1 <= text1.length, text2.length <= 1000`
42+
* `text1` 和 `text2` 仅由小写英文字符组成。
43+
44+
---
45+
46+
动态规划:
47+
48+
定义 `dp[i][j]``text1[0:i]``text2[0:j]` 的最长公共子序列的长度。
49+
50+
状态转移方程为:当 `text1[i] == text2[j]` 时,`dp[i][j] = dp[i - 1][j - 1] + 1`;当 `text1[i] != text2[j]` 时,`dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])`
51+
52+
```Java
53+
class Solution {
54+
public int longestCommonSubsequence(String text1, String text2) {
55+
int m = text1.length(), n = text2.length();
56+
int[][] dp = new int[m + 1][n + 1];
57+
for(int i = 1; i <= m; i++){
58+
for(int j = 1; j <= n; j++){
59+
if(text1.charAt(i - 1) == text2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1;
60+
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
61+
}
62+
}
63+
return dp[m][n];
64+
}
65+
}
66+
```

0 commit comments

Comments
 (0)