LeetCode 题解工作台

最长回文子序列

给你一个字符串 s ,找出其中最长的回文子序列,并返回该序列的长度。 子序列定义为:不改变剩余字符顺序的情况下,删除某些字符或者不删除任何字符形成的一个序列。 示例 1: 输入: s = "bbbab" 输出: 4 解释: 一个可能的最长回文子序列为 "bbbb" 。 示例 2: 输入: s = "…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示字符串 的第 个字符到第 个字符之间的最长回文子序列的长度。初始时 $f[i][i] = 1$,其余位置的值均为 。 如果 $s[i] = s[j]$,那么 $f[i][j] = f[i + 1][j - 1] + 2$;否则 $f[i][j] = \max(f[i + 1][j], f[i][j - 1])$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,找出其中最长的回文子序列,并返回该序列的长度。

子序列定义为:不改变剩余字符顺序的情况下,删除某些字符或者不删除任何字符形成的一个序列。

 

示例 1:

输入:s = "bbbab"
输出:4
解释:一个可能的最长回文子序列为 "bbbb" 。

示例 2:

输入:s = "cbbd"
输出:2
解释:一个可能的最长回文子序列为 "bb" 。

 

提示:

  • 1 <= s.length <= 1000
  • s 仅由小写英文字母组成
lightbulb

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 表示字符串 ss 的第 ii 个字符到第 jj 个字符之间的最长回文子序列的长度。初始时 f[i][i]=1f[i][i] = 1,其余位置的值均为 00

如果 s[i]=s[j]s[i] = s[j],那么 f[i][j]=f[i+1][j1]+2f[i][j] = f[i + 1][j - 1] + 2;否则 f[i][j]=max(f[i+1][j],f[i][j1])f[i][j] = \max(f[i + 1][j], f[i][j - 1])

由于 f[i][j]f[i][j] 的值与 f[i+1][j1]f[i + 1][j - 1], f[i+1][j]f[i + 1][j], f[i][j1]f[i][j - 1] 有关,所以我们应该从大到小枚举 ii,从小到大枚举 jj

答案即为 f[0][n1]f[0][n - 1]

时间复杂度 O(n2)O(n^2),空间复杂度 O(n2)O(n^2)。其中 nn 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        n = len(s)
        f = [[0] * n for _ in range(n)]
        for i in range(n):
            f[i][i] = 1
        for i in range(n - 1, -1, -1):
            for j in range(i + 1, n):
                if s[i] == s[j]:
                    f[i][j] = f[i + 1][j - 1] + 2
                else:
                    f[i][j] = max(f[i + 1][j], f[i][j - 1])
        return f[0][-1]
speed

复杂度分析

指标
时间complexity is O(n^2) due to iterating all substring ranges and updating the dp table. Space complexity is O(n^2) for the dp array, though it can be optimized to O(n) using a single rolling array along diagonals.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expecting use of dynamic programming rather than brute force recursion due to overlapping subproblems.

  • question_mark

    Watch for correct handling of single-character substrings and matching endpoints.

  • question_mark

    Check that candidates optimize state transitions and avoid unnecessary recomputation.

warning

常见陷阱

外企场景
  • error

    Confusing subsequence with substring, which leads to incorrect dp updates.

  • error

    Failing to correctly initialize dp for single-character substrings.

  • error

    Overwriting dp values too early, which can break dependencies for longer substrings.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the actual longest palindromic subsequence string, not just its length.

  • arrow_right_alt

    Compute the minimum number of deletions to make the string a palindrome using the same dp logic.

  • arrow_right_alt

    Handle strings with both uppercase and lowercase letters while maintaining the longest palindromic subsequence.

help

常见问题

外企场景

最长回文子序列题解:状态·转移·动态规划 | LeetCode #516 中等