tinycodinglm / cp /cp-10023.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.69 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Longest Palindromic Subsequence (Difficulty: Medium)
Tags: String, Dynamic Programming

Given a string s, find the longest palindromic subsequence's length in s.
A 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.

Example 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".

Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".

Constraints:

  • 1 <= s.length <= 1000
  • s consists only of lowercase English letters.
Assistant

Time: O(n^2)

Space: O(n)

class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
if s == s[::-1]: # optional, to optimize special case
return len(s)

markdown
dp = [[1] * len(s) for _ in range(2)]
    for i in reversed(range(len(s))):
        for j in range(i+1, len(s)):
            if s[i] == s[j]:
                dp[i%2][j] = 2 + dp[(i+1)%2][j-1] if i+1 <= j-1 else 2
            else:
                dp[i%2][j] = max(dp[(i+1)%2][j], dp[i%2][j-1])
    return dp[0][-1]