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 39b13dd6de824bf00c4fc0c6bdb54fa236b10cb9..0694da5870284009ac26d8c4365447b4242c781c 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" @@ -173,3 +173,25 @@ public int longestCommonSubsequence(String text1, String text2) { } ``` +[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] +``` +