添加1143.最长公共子序列 Java/Python版本

This commit is contained in:
LehiChiang
2021-05-13 19:06:13 +08:00
parent 49eed9c8a3
commit b52d12bd37

View File

@ -31,7 +31,7 @@
输入text1 = "abc", text2 = "def" 输入text1 = "abc", text2 = "def"
输出0 输出0
解释:两个字符串没有公共子序列,返回 0。 解释:两个字符串没有公共子序列,返回 0。
 
提示: 提示:
* 1 <= text1.length <= 1000 * 1 <= text1.length <= 1000
* 1 <= text2.length <= 1000 * 1 <= text2.length <= 1000
@ -126,12 +126,44 @@ public:
## 其他语言版本 ## 其他语言版本
Java 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
```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 Go