给你一个字符串 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-insertion-steps-to-make-a-string-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
f(l,r)表示把 l - r 这一段变为回文串的所有可能操作中次数最少的那种次数。f(l + 1, r - 1), f(l, r - 1), f(l + 1, r)都是已知的。所以有三种操作可能:l==r,什么操作都不需要,如果不相等,就在右边或左边加一个字母。
class Solution {
public:
int f[510][510];
int minInsertions(string s) {
memset(f, -1, sizeof f);
return dp(s, 0, s.length() - 1);
}
int dp(string& s, int l, int r)
{
if(l >= r) return 0;
if(f[l][r] != -1) return f[l][r];
if(s[l] == s[r]) return f[l][r] = dp(s, l + 1, r - 1);
return f[l][r] = min(dp(s, l + 1, r), dp(s, l, r - 1)) + 1;
}
};