Minimum Insertion Steps to Make a String Palindrome in C++

C++Server Side ProgrammingProgramming

Suppose we have a string s, we have to make this string palindrome. in each step we can insert any character at any position, we have to find minimum number of characters that require to make this palindrome. If the string is like “mad”, then the answer will be 2 as we can add “da” before “mad”, or “am” after “mad” to make this palindrome.

To solve this, we will follow these steps −

  • Define a function lcs(), this will take s, x := s
  • n := size of s
  • reverse the string x
  • s := concatenate space before s, x := concatenate space before x
  • Define one 2D array dp of size (n + 1) x (n + 1)
  • for initialize i := 1, when i <= n, update (increase i by 1), do −
    • for initialize j := 1, when j <= n, update (increase j by 1), do −
      • dp[i, j] := maximum of dp[i – 1, j] and dp[i, j - 1]
      • if s[i] is same as x[j], then −
        • dp[i, j] := maximum of dp[i, j] and dp[i – 1, j - 1] + 1
  • return dp[n, n]
  • From the main method return size of s – lcs(s)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int lcs(string s){
      string x = s;
      int n = s.size();
      reverse(x.begin(), x.end());
      s = " " + s;
      x = " " + x;
      vector < vector <int> > dp(n + 1, vector <int>(n + 1));
      for(int i = 1; i <= n; i++){
         for(int j = 1; j <= n; j++){
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            if(s[i] == x[j]){
               dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
            }
         }
      }
      return dp[n][n];
   }
   int minInsertions(string s) {
      return s.size() - lcs(s);
   }
};
main(){
   Solution ob;
   cout << (ob.minInsertions("mad"));
}

Input

“mad”

Output

2
raja
Published on 02-Jun-2020 11:35:33
Advertisements