給你一個字符串 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;
}
};