1312. 让字符串成为回文串的最少插入次数(leetcode)
题目描述
给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。
请你返回让 s 成为回文串的 最少操作次数 。
「回文串」是正读和反读都相同的字符串。
示例1
输入:s = “zzazz”
输出:0
解释:字符串 “zzazz” 已经是回文串了,所以不需要做任何插入操作。
示例2
输入:s = “mbadm”
输出:2
解释:字符串可变为 “mbdadbm” 或者 “mdbabdm” 。
示例3
输入:s = “leetcode”
输出:5
解释:插入 5 个字符后字符串变为 “leetcodocteel” 。
提示信息
1 <= s.length <= 500
s 中所有字符都是小写字母。
题解1(C++版本)
class Solution {
public:
int dp[510][510]; // dp[L][R]表示让s[L,R]这段子串成为回文串的最少操作次数
int dfs(string& s,int L, int R){
if(L >= R) return 0;
if(dp[L][R] != 0x3f3f3f3f) return dp[L][R];
if(s[L] == s[R]) return dp[L][R] = dfs(s, L + 1, R - 1);
return dp[L][R] = min(dfs(s, L + 1, R), dfs(s, L, R - 1)) + 1;
}
int minInsertions(string s) {
int n = s.size();
memset(dp, 0x3f, sizeof dp);
return dfs(s, 0, n - 1);
}
};