File size: 1,694 Bytes
3c88a0f
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cp-10023", "name": "LeetCode 0516: Longest Palindromic Subsequence"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Longest Palindromic Subsequence (Difficulty: Medium)\nTags: String, Dynamic Programming\n\nGiven a string s, find the longest palindromic subsequence's length in s.\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\nExample 1:\nInput: s = \"bbbab\"\nOutput: 4\nExplanation: One possible longest palindromic subsequence is \"bbbb\".\n\nExample 2:\nInput: s = \"cbbd\"\nOutput: 2\nExplanation: One possible longest palindromic subsequence is \"bb\".\n\nConstraints:\n- 1 <= s.length <= 1000\n- s consists only of lowercase English letters."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time:  O(n^2)\n# Space: O(n)\n\nclass Solution(object):\n    def longestPalindromeSubseq(self, s):\n        \"\"\"\n        :type s: str\n        :rtype: int\n        \"\"\"\n        if s == s[::-1]:  # optional, to optimize special case\n            return len(s)\n\n        dp = [[1] * len(s) for _ in range(2)]\n        for i in reversed(range(len(s))):\n            for j in range(i+1, len(s)):\n                if s[i] == s[j]:\n                    dp[i%2][j] = 2 + dp[(i+1)%2][j-1] if i+1 <= j-1 else 2\n                else:\n                    dp[i%2][j] = max(dp[(i+1)%2][j], dp[i%2][j-1])\n        return dp[0][-1]\n\n"}}