Minimum Insertion Steps to Make a String Palindrome

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.

Palindrome String is one that reads the same backward as well as forward.

Example:

Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int minInsertions(string s)
{
    int n = s.length();
    vector<intdp(n0);
    int i = 0j = 0;

    for (i = 0j = n - 1i <= ji++, j--)
    {
        if (s[i] != s[j])
            break;
    }

    //if already palindrome
    if (i > j)
        return 0;

    for (i = n - 2i >= 0i--)
    {
        int pre = 0;
        for (j = i + 1j < nj++)
        {
            int temp = dp[j];
            if (s[i] == s[j])
                dp[j] = pre;
            else
            {
                dp[j] = min(dp[j]dp[j - 1]) + 1;
            }
            pre = temp;
        }
    }

    return dp[n - 1];
}

int main()
{
    string s = "mbadm";

    cout << minInsertions(s);

    return 0;
}


No comments:

Post a Comment