From 00fe4546368d091b627a78ff69a6d7a683f78c5b Mon Sep 17 00:00:00 2001 From: lo-tp Date: Fri, 13 Nov 2020 13:36:16 +0800 Subject: [PATCH] =?UTF-8?q?[1143.=20=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=88=97]=20python?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...61\345\255\220\345\272\217\345\210\227.md" | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) 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 39b13dd..0694da5 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] +``` + -- GitLab