LeetCode 题解工作台

让字符串成为回文串的最少插入次数

给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。 请你返回让 s 成为回文串的 最少操作次数 。 「回文串」是正读和反读都相同的字符串。 示例 1: 输入: s = "zzazz" 输出: 0 解释: 字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。 示例 …

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

bolt

答案摘要

我们设计一个函数 $dfs(i, j)$,表示将字符串 变成回文串所需要的最少操作次数。那么答案就是 $dfs(0, n - 1)$。 函数 $dfs(i, j)$ 的计算过程如下:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。

请你返回让 s 成为回文串的 最少操作次数 。

「回文串」是正读和反读都相同的字符串。

 

示例 1:

输入:s = "zzazz"
输出:0
解释:字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。

示例 2:

输入:s = "mbadm"
输出:2
解释:字符串可变为 "mbdadbm" 或者 "mdbabdm" 。

示例 3:

输入:s = "leetcode"
输出:5
解释:插入 5 个字符后字符串变为 "leetcodocteel" 。

 

提示:

  • 1 <= s.length <= 500
  • s 中所有字符都是小写字母。
lightbulb

解题思路

方法一:记忆化搜索

我们设计一个函数 dfs(i,j)dfs(i, j),表示将字符串 s[i..j]s[i..j] 变成回文串所需要的最少操作次数。那么答案就是 dfs(0,n1)dfs(0, n - 1)

函数 dfs(i,j)dfs(i, j) 的计算过程如下:

如果 iji \geq j,此时无需插入任何字符,我们直接返回 00

否则,我们判断 s[i]s[i]s[j]s[j] 是否相等,如果 s[i]=s[j]s[i]=s[j],那么我们只需要将 s[i+1..j1]s[i+1..j-1] 变成回文串,那么我们返回 dfs(i+1,j1)dfs(i + 1, j - 1)。否则,我们可以在 s[i]s[i] 的左侧或者 s[j]s[j] 的右侧插入一个与另一侧相同的字符,那么 dfs(i,j)=min(dfs(i+1,j),dfs(i,j1))+1dfs(i, j) = \min(dfs(i + 1, j), dfs(i, j - 1)) + 1

为了避免重复计算,我们可以使用记忆化搜索,即使用哈希表或者数组来存储已经计算过的函数值。

最后,我们返回 dfs(0,n1)dfs(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
class Solution:
    def minInsertions(self, s: str) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= j:
                return 0
            if s[i] == s[j]:
                return dfs(i + 1, j - 1)
            return 1 + min(dfs(i + 1, j), dfs(i, j - 1))

        return dfs(0, len(s) - 1)
speed

复杂度分析

指标
时间O(n^2)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Understanding dynamic programming concepts is key.

  • question_mark

    Ability to optimize space complexity is important.

  • question_mark

    Problem-solving skills for state transition dynamic programming are crucial.

warning

常见陷阱

外企场景
  • error

    Forgetting to account for single character substrings as palindromes.

  • error

    Improperly updating the DP table, leading to incorrect results.

  • error

    Failing to optimize space complexity, leading to unnecessary memory usage.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Limit the number of insertions to a fixed number.

  • arrow_right_alt

    Modify the problem to find the longest palindromic subsequence instead of minimum insertions.

  • arrow_right_alt

    Extend the problem to work with multi-character insertions or deletions.

help

常见问题

外企场景

让字符串成为回文串的最少插入次数题解:状态·转移·动态规划 | LeetCode #1312 困难