未验证 提交 c1cec9e9 编写于 作者: B BruceCat 提交者: GitHub

【1143. 最长公共子序列】【python】

【1143. 最长公共子序列】【python】
......@@ -149,6 +149,7 @@ else:
======其他语言代码======
### c++
[Edwenc](https://github.com/Edwenc) 提供 C++ 代码:
......@@ -183,6 +184,8 @@ public:
};
```
### java
[Shawn](https://github.com/Shawn-Hx) 提供 Java 代码:
```java
......@@ -207,4 +210,28 @@ public int longestCommonSubsequence(String text1, String text2) {
}
```
### python
[lo-tp](http://blog.lotp.xyz/) 提供 Python 代码:
```python
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
# calculate the size of the first and second string
sz1, sz2 = len(text1), len(text2)
# since to calculate dp(i,j) we only need dp(i-1,j-1), dp(i-1,j), dp(i,j-1)
# we don't have to save data before i-1
# we use dp to save dp(i-1, 0), dp(i-1, 1)....dp(i-1, sz2)
# we use tmp to save dp(i, 0), dp(i,1)....(dpi-1, sz2)
tmp, dp = [0]*(sz2+1), [0]*(sz2+1)
for i in range(0, sz1):
for j in range(0, sz2):
tmp[j+1] = dp[j] + \
1 if text1[i] == text2[j] else max(tmp[j], dp[j+1])
# In the next iteration, we will calculate dp(i+1,0),dp(i+1, 1)....dp(i+1,sz2)
# So we exchange dp and tmp
tmp, dp = dp, tmp
return dp[-1]
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册