LeetCode 题解工作台
让字符串成为回文串的最少插入次数
给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。 请你返回让 s 成为回文串的 最少操作次数 。 「回文串」是正读和反读都相同的字符串。 示例 1: 输入: s = "zzazz" 输出: 0 解释: 字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。 示例 …
2
题型
4
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们设计一个函数 $dfs(i, j)$,表示将字符串 变成回文串所需要的最少操作次数。那么答案就是 $dfs(0, n - 1)$。 函数 $dfs(i, j)$ 的计算过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。
请你返回让 s 成为回文串的 最少操作次数 。
「回文串」是正读和反读都相同的字符串。
示例 1:
输入:s = "zzazz" 输出:0 解释:字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。
示例 2:
输入:s = "mbadm" 输出:2 解释:字符串可变为 "mbdadbm" 或者 "mdbabdm" 。
示例 3:
输入:s = "leetcode" 输出:5 解释:插入 5 个字符后字符串变为 "leetcodocteel" 。
提示:
1 <= s.length <= 500s中所有字符都是小写字母。
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示将字符串 变成回文串所需要的最少操作次数。那么答案就是 。
函数 的计算过程如下:
如果 ,此时无需插入任何字符,我们直接返回 。
否则,我们判断 与 是否相等,如果 ,那么我们只需要将 变成回文串,那么我们返回 。否则,我们可以在 的左侧或者 的右侧插入一个与另一侧相同的字符,那么 。
为了避免重复计算,我们可以使用记忆化搜索,即使用哈希表或者数组来存储已经计算过的函数值。
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n^2) |
| 空间 | O(n) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.