让字符串成为回文串的最少插入次数
难度:
标签:
题目描述
代码结果
运行时间: 138 ms, 内存: 16.0 MB
/*
* Problem: Given a string s, you can insert characters at any position to make it a palindrome.
* You need to find the minimum number of insertion operations required.
* A palindrome is a string that reads the same backward as forward.
*
* Approach:
* 1. We need to find the longest palindromic subsequence (LPS) in the string.
* 2. The minimum number of insertions required will be the length of the string minus the length of the LPS.
* 3. Use dynamic programming to find the LPS.
* 4. Java Streams are not well-suited for this problem's dynamic programming approach,
* hence using standard Java.
*/
public class SolutionStream {
public int minInsertions(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) dp[i][i] = 1;
for (int len = 2; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
int j = i + len - 1;
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
int lps = dp[0][n - 1];
return n - lps;
}
}
解释
方法:
本题解通过动态规划方法求解字符串成为回文串的最少插入次数。思路是先求出给定字符串的最长回文子序列的长度(使用动态规划表dp),然后用字符串的总长度减去这个最长回文子序列的长度,得到的结果即为最少的插入次数。动态规划表dp[i]表示从索引i到字符串末尾的子字符串中的最长回文子序列的长度。通过逐个比较字符,如果字符相同,则更新dp表;如果不同,则将dp[j]更新为dp[j]和dp[j-1]中的较大值。
时间复杂度:
O(n^2)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在动态规划的基础上,最终的结果是用字符串的长度减去最长回文子序列的长度得到的?
▷🦆
在动态规划过程中,temp变量的具体作用是什么?为什么需要使用它来帮助更新dp数组?
▷🦆
动态规划解法中,为什么将dp数组的每个元素初始化为1而不是0?
▷🦆
代码中的嵌套循环结构如何确保能够正确更新dp数组来反映最长回文子序列的长度?
▷