class Solution {
/**
To make a string a palindrome with minimum insertions,
we try to keep the largest palindromic part of the string unchanged and insert characters for the rest.
Minimum Insertions=n−LPS length
Minimum Deletion=n−LPS length
1. Reverse the string and store it in new string
2. Find Longest Common Subsequence (LCS) between s and reverse(s).
3. That LCS is the Longest Palindromic Subsequence.
*/
public int minInsertions
(String s
) { String s2
= new StringBuilder
(s
).
reverse().
toString();
int n = s.length();
int m = s2.length();
// create a matrix
int[][] t = new int[n+1][m+1];
// initialise the matrix
for(int i=0; i<n+1; i++)
{
for(int j=0; j<m+1; j++)
{
if(i == 0 || j == 0)
t[i][j] = 0;
}
}
// find LCS
for(int i=1; i<n+1; i++)
{
for(int j=1; j<m+1; j++)
{
if(s.charAt(i-1) == s2.charAt(j-1))
{
t[i][j] = 1 + t[i-1][j-1];
}
else
t
[i
][j
] = Math.
max(t
[i
-1][j
], t
[i
][j
-1]); }
}
int lcsLength = t[n][m];
return (n-lcsLength);
}
}
// s= zzazz
// t= zzazz
// LCS: zzazz
// s= mbadm
// t= mdabm
// LCS: mam = 3
// No of deletion = n-lcs = 5-3 = 2
// no of insertion = m - lcs = 5-3 = 2