mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加1143.最长公共子序列 Java/Python版本
This commit is contained in:
@ -31,7 +31,7 @@
|
||||
输入:text1 = "abc", text2 = "def"
|
||||
输出:0
|
||||
解释:两个字符串没有公共子序列,返回 0。
|
||||
|
||||
|
||||
提示:
|
||||
* 1 <= text1.length <= 1000
|
||||
* 1 <= text2.length <= 1000
|
||||
@ -126,12 +126,44 @@ public:
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
|
||||
Java:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int longestCommonSubsequence(String text1, String text2) {
|
||||
int[][] dp = new int[text1.length() + 1][text2.length() + 1]; // 先对dp数组做初始化操作
|
||||
for (int i = 1 ; i <= text1.length() ; i++) {
|
||||
char char1 = text1.charAt(i - 1);
|
||||
for (int j = 1; j <= text2.length(); j++) {
|
||||
char char2 = text2.charAt(j - 1);
|
||||
if (char1 == char2) { // 开始列出状态转移方程
|
||||
dp[i][j] = dp[i - 1][j - 1] + 1;
|
||||
} else {
|
||||
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[text1.length()][text2.length()];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
|
||||
len1, len2 = len(text1)+1, len(text2)+1
|
||||
dp = [[0 for _ in range(len1)] for _ in range(len2)] # 先对dp数组做初始化操作
|
||||
for i in range(1, len2):
|
||||
for j in range(1, len1): # 开始列出状态转移方程
|
||||
if text1[j-1] == text2[i-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[-1][-1]
|
||||
```
|
||||
|
||||
|
||||
Go:
|
||||
|
||||
@ -142,4 +174,4 @@ Go:
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
Reference in New Issue
Block a user