@@ -149,6 +149,7 @@ else:
149149
150150======其他语言代码======
151151
152+ ### c++
152153
153154[ Edwenc] ( https://github.com/Edwenc ) 提供 C++ 代码:
154155
@@ -183,6 +184,8 @@ public:
183184};
184185```
185186
187+ ### java
188+
186189[ Shawn] ( https://github.com/Shawn-Hx ) 提供 Java 代码:
187190
188191``` java
@@ -207,4 +210,28 @@ public int longestCommonSubsequence(String text1, String text2) {
207210}
208211```
209212
213+ ### python
214+
215+ [ lo-tp] ( http://blog.lotp.xyz/ ) 提供 Python 代码:
216+
217+ ``` python
218+ class Solution (object ):
219+ def longestCommonSubsequence (self , text1 , text2 ):
220+ # calculate the size of the first and second string
221+ sz1, sz2 = len (text1), len (text2)
222+ # since to calculate dp(i,j) we only need dp(i-1,j-1), dp(i-1,j), dp(i,j-1)
223+ # we don't have to save data before i-1
224+ # we use dp to save dp(i-1, 0), dp(i-1, 1)....dp(i-1, sz2)
225+ # we use tmp to save dp(i, 0), dp(i,1)....(dpi-1, sz2)
226+ tmp, dp = [0 ]* (sz2+ 1 ), [0 ]* (sz2+ 1 )
227+ for i in range (0 , sz1):
228+ for j in range (0 , sz2):
229+ tmp[j+ 1 ] = dp[j] + \
230+ 1 if text1[i] == text2[j] else max (tmp[j], dp[j+ 1 ])
231+ # In the next iteration, we will calculate dp(i+1,0),dp(i+1, 1)....dp(i+1,sz2)
232+ # So we exchange dp and tmp
233+ tmp, dp = dp, tmp
234+ return dp[- 1 ]
235+ ```
236+
210237
0 commit comments