| 
 | 1 | +# Time: O(n^2) Space: O(n^2) - For all three solutions  | 
 | 2 | +class Solution:  | 
 | 3 | +    def longestPalindromeSubseq(self, s: str) -> int:     | 
 | 4 | +        # Dynamic Programming  | 
 | 5 | +        dp = [ [0] * (len(s) + 1) for i in range(len(s) + 1)]  | 
 | 6 | +        res = 0  | 
 | 7 | +          | 
 | 8 | +        for i in range(len(s)):  | 
 | 9 | +            for j in range(len(s) - 1, i - 1, -1):  | 
 | 10 | +                if s[i] == s[j]:  | 
 | 11 | +                    dp[i][j] = 1 if i == j else 2  | 
 | 12 | +                    if i - 1 >= 0:  | 
 | 13 | +                        dp[i][j] += dp[i - 1][j + 1]  | 
 | 14 | +                else:  | 
 | 15 | +                    dp[i][j] = dp[i][j + 1]  | 
 | 16 | +                    if i - 1 >= 0:  | 
 | 17 | +                        dp[i][j] = max(dp[i][j], dp[i - 1][j])  | 
 | 18 | +                res = max(res, dp[i][j])  | 
 | 19 | +        return res  | 
 | 20 | + | 
 | 21 | + | 
 | 22 | +        # Memoization  | 
 | 23 | +        cache = {}  | 
 | 24 | + | 
 | 25 | +        def dfs(i, j):  | 
 | 26 | +            if i < 0 or j == len(s):  | 
 | 27 | +                return 0  | 
 | 28 | +            if (i, j) in cache:  | 
 | 29 | +                return cache[(i, j)]  | 
 | 30 | + | 
 | 31 | +            if s[i] == s[j]:  | 
 | 32 | +                length = 1 if i == j else 2  | 
 | 33 | +                cache[(i, j)] = length + dfs(i - 1, j + 1)  | 
 | 34 | +            else:  | 
 | 35 | +                cache[(i, j)] = max(dfs(i - 1, j), dfs(i, j + 1))  | 
 | 36 | +            return cache[(i, j)]  | 
 | 37 | +          | 
 | 38 | +        for i in range(len(s)):  | 
 | 39 | +            dfs(i, i) # odd length  | 
 | 40 | +            dfs(i, i + 1) # even length  | 
 | 41 | + | 
 | 42 | +        return max(cache.values())  | 
 | 43 | +          | 
 | 44 | +# LCS Solution  | 
 | 45 | +class Solution:  | 
 | 46 | +    def longestPalindromeSubseq(self, s: str) -> int:  | 
 | 47 | +        return self.longestCommonSubsequence(s, s[::-1])  | 
 | 48 | +          | 
 | 49 | +      | 
 | 50 | +    def longestCommonSubsequence(self, s1: str, s2: str) -> int:  | 
 | 51 | +        N, M = len(s1), len(s2)  | 
 | 52 | +        dp = [[0] * (M+1) for _ in range(N+1)]  | 
 | 53 | + | 
 | 54 | +        for i in range(N):  | 
 | 55 | +            for j in range(M):  | 
 | 56 | +                if s1[i] == s2[j]:  | 
 | 57 | +                    dp[i+1][j+1] = 1 + dp[i][j]  | 
 | 58 | +                else:  | 
 | 59 | +                    dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])  | 
 | 60 | +        return dp[N][M]  | 
0 commit comments