Given a string s. In one step you can insert any character at any index of the string.

Return the minimum number of steps to make s palindrome.

idea:

sounds like a edit distance kind of problem, and can we do it in DP?

this is like we have a palindrome string and a non palindrome one(the input) and checking the insertion we have to made this non palindrome to palindrome.

and we know that there are many ways to make this palindrome, the worst should be add (n-1) letters to make this string palindrome.

so how do we solve this problem?

we split the input s into two parts, now we have two parts, then if the first part is the reverse of second part, then we got one palindrome, if not, then we check the how many char we need to add in order to make them equal. the more LCS between s1 and reverse(s2), the less we will need. we only needs to add n - LCS(s1, reverse(s2)) (也就是说 在s1中补充s2.length() - LCS(), 在s2中补充s1.length() - LCS)

//where dp[i][j] means the length of longest common sequence between i first letters in s1 and j first letters in s2.
class Solution {
public int minInsertions(String s) {
int n = s.length();
int[][] dp = new int[n+1][n+1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { //ij组合有n*n种 for each combination we need to calculate the LCS of
if (s.charAt(i) == s.charAt(n - 1 - j)) { //for charAt
dp[i+1][j+1] = dp[i][j] + 1;
//LCS of
} else { //if they are not the same, then it means the LCS of those two will be delete either one of them
dp[i+1][j+1] = Math.max(dp[i][j+1], dp[i+1][j]); //the longer LCS , the less we gonna add
}
}
}
return n - dp[n][n];
}
}

this is genius…