import java.util.*;
/**
* NC376 变回文串的最少插入次数
* @author d3y1
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @return int整型
*/
public int minInsert (String str) {
return solution(str);
}
/**
* 动态规划
*
* dp[i][j]表示字符串str子串[i,j]变成回文串的最少插入次数
*
* { dp[i+1][j-1] , str.charAt(i)=str.charAt(j)
* dp[i][j] = {
* { Math.min(dp[i+1][j], dp[i][j-1])+1 , str.charAt(i)!=str.charAt(j)
*
* @param str
* @return
*/
private int solution(String str){
int len = str.length();
int[][] dp = new int[len][len];
for(int i=len-2; i>=0; i--){
for(int j=i+1; j<len; j++){
if(str.charAt(i) == str.charAt(j)){
dp[i][j] = dp[i+1][j-1];
}else{
dp[i][j] = Math.min(dp[i+1][j], dp[i][j-1])+1;
}
}
}
return dp[0][len-1];
}
}