题目描述:
给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。
请你返回让 s 成为回文串的 最少操作次数 。
「回文串」是正读和反读都相同的字符串。
示例 1:
输入:s = “zzazz”
输出:0
解释:字符串 “zzazz” 已经是回文串了,所以不需要做任何插入操作。
示例 2:
输入:s = “mbadm”
输出:2
解释:字符串可变为 “mbdadbm” 或者 “mdbabdm” 。
示例 3:
输入:s = “leetcode”
输出:5
解释:插入 5 个字符后字符串变为 “leetcodocteel” 。
示例 4:
输入:s = “g”
输出:0
示例 5:
输入:s = “no”
输出:1
提示:
1 <= s.length <= 500
s 中所有字符都是小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-insertion-steps-to-make-a-string-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我想到的是动态规划
其实比较简单:
class Solution {
public int minInsertions(String s) {
int dp [][] = new int[s.length() + 1][s.length() + 1];
for (int i = 0; i < s.length() - 1; i++) {
if(s.charAt(i) != s.charAt(i + 1)){
dp[i][i + 1] = 1;
}
}
// 长度的遍历
for (int i = 2; i < s.length(); i++) {
// 索引的遍历
for (int j = 0; j < s.length(); j++) {
int end = j + i;
if(end >= s.length()){
break;
}
if(s.charAt(j) == s.charAt(end)){
dp[j][end] = dp[j + 1][end - 1];
}else{
dp[j][end] = Math.min(dp[j + 1][end],dp[j][end - 1]) + 1;
}
}
}
return dp[0][s.length() - 1];
}
}