diff --git "a/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" "b/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" index 7117ba90a21bc7b5ca43771f341be8525a815c5e..1fe1cfbd5542c94925d467bd98d94ecf9e2419f6 100644 --- "a/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" +++ "b/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" @@ -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] +``` +