Form a palindrome

PROBLEM :
Given a string, find the minimum number of characters to be inserted to convert it to palindrome.
For Example:
ab: Number of insertions required is 1. bab or aba
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd

Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is S.

Output:
Print the minimum number of characters.

Constraints:
1 = T = 50
1 = S = 40

Example:
Input:
3
abcd
aba
geeks

Output:
3
0
3

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<string.h>
#include<iostream>
using namespace std;
int Form_a_palindrome(string ) ;
string reverse_string(string ,int ) ;
int min(int ,int ,int ) ;
int main()
{
int t ;
string str ;
cin>>t ;
while(t--)
{
   cin>>str ;
   cout<<Form_a_palindrome(str)<<endl ;
}
return 0;
}

int Form_a_palindrome(string str)
{
    int i,len,j,max ;
    len=str.length() ;
    max=0 ;
   
    string revs=reverse_string(str,len) ;
    int temp[len+1][len+1] ;
   
    for(i=0;i<=len;i++)
    {
        temp[i][0]=0 ;
        temp[0][i]=0 ;
    }
   
    for(i=1;i<=len;i++)
    {
        for(j=1;j<=len;j++)
        {
            if(str[i-1]==revs[j-1])
                temp[i][j]=temp[i-1][j-1]+1 ;
            else
                temp[i][j]=temp[i-1][j]>temp[i][j-1]?temp[i-1][j]:temp[i][j-1] ;
               
            max=max>temp[i][j]?max:temp[i][j] ;
        }
    }
    return len-max ;
}

string reverse_string(string str,int no)
{
    int i ;
    char temp ;
    i=0 ;
    no-- ;
   
    while(i<no)
    {
        temp=str[i] ;
        str[i]=str[no] ;
        str[no]=temp ;
       
        i++ ;
        no-- ;
    }
    return str ;
}

int min(int a,int b,int c)
{
int temp,min ;
    temp = (a<b)?a:b;
    min=(c<temp)?c:temp;
    return min ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )