|
| 1 | +# time complexity: O(n*m) |
| 2 | +# space compleixty: O(n*m) |
| 3 | + |
| 4 | +# Bottom Up |
| 5 | +from functools import lru_cache |
| 6 | + |
| 7 | + |
| 8 | +class Solution: |
| 9 | + def longestCommonSubsequence(self, text1: str, text2: str) -> int: |
| 10 | + T1 = len(text1) |
| 11 | + T2 = len(text2) |
| 12 | + dp = [[0 for _ in range(T2 + 1)] for _ in range(T1 + 1)] |
| 13 | + for t1 in range(1, T1 + 1): |
| 14 | + for t2 in range(1, T2 + 1): |
| 15 | + if text1[t1 - 1] == text2[t2 - 1]: |
| 16 | + dp[t1][t2] = dp[t1 - 1][t2 - 1] + 1 |
| 17 | + else: |
| 18 | + dp[t1][t2] = max(dp[t1 - 1][t2], dp[t1][t2 - 1]) |
| 19 | + |
| 20 | + return dp[T1][T2] |
| 21 | + |
| 22 | + |
| 23 | +# time complexity: O(n*m) |
| 24 | +# space compleixty: O(n*m) |
| 25 | + |
| 26 | +# Top Down |
| 27 | +class Solution: |
| 28 | + def longestCommonSubsequence(self, text1: str, text2: str) -> int: |
| 29 | + T1 = len(text1) |
| 30 | + T2 = len(text2) |
| 31 | + dp = [[0 for _ in range(T2 + 1)] for _ in range(T1 + 1)] |
| 32 | + for t1 in range(T1): |
| 33 | + for t2 in range(T2): |
| 34 | + if text1[t1] == text2[t2]: |
| 35 | + if t1 == 0 and t2 == 0: |
| 36 | + dp[t1][t2] = 1 |
| 37 | + else: |
| 38 | + dp[t1][t2] = dp[t1-1][t2-1] + 1 |
| 39 | + if t1 > 0 and dp[t1-1][t2] > dp[t1][t2]: |
| 40 | + dp[t1][t2] = dp[t1-1][t2] |
| 41 | + if t2 > 0 and dp[t1][t2-1] > dp[t1][t2]: |
| 42 | + dp[t1][t2] = dp[t1][t2-1] |
| 43 | + return dp[T1 - 1][T2 - 1] |
| 44 | + |
| 45 | + |
| 46 | +class Solution: |
| 47 | + def longestCommonSubsequence(self, text1: str, text2: str) -> int: |
| 48 | + @lru_cache(None) |
| 49 | + def dp(p1: int, p2: int): |
| 50 | + if p1 == len(text1) or p2 == len(text2): |
| 51 | + return 0 |
| 52 | + if text1[p1] == text2[p2]: |
| 53 | + return 1 + dp(p1 + 1, p2 + 1) |
| 54 | + else: |
| 55 | + return max(dp(p1, p2 + 1), dp(p1 + 1, p2)) |
| 56 | + return dp(0, 0) |
| 57 | + |
| 58 | + |
| 59 | +text1 = "abcde" |
| 60 | +text2 = "ace" |
| 61 | +print(Solution().longestCommonSubsequence(text1, text2)) |
| 62 | +text1 = "abc" |
| 63 | +text2 = "abc" |
| 64 | +print(Solution().longestCommonSubsequence(text1, text2)) |
| 65 | +text1 = "abc" |
| 66 | +text2 = "def" |
| 67 | +print(Solution().longestCommonSubsequence(text1, text2)) |
0 commit comments