Palindromic Strings

PROBLEM :
Given a string you have to transform it into a palindrome . In order to acheive that you have to perform exactly k insertion of characters(you cannot perform any more or less number of insertions).Now you have to report whether the string can be converted to a palindrome by making exactly k insertions.

Input :
The first line contains the number of test cases T. For each test case the first line contains the length of the string N and the number of insertions k. The second line contains the string S.

Output :
For each test case, print "YES"(without quotes) if the string can be converted to a palindrome making exactly k insertions otherwise "NO"(without quotes).

Constraints :
1 = T = 100
0<=k<=100000
The string consists of only lower case English Alphabets (a-z).

Example:
Input :
2
4 2
abac
5 3
abcde

Output :
YES
NO

Explanation :

For the first test case abac can be transformed to cabbac (which is palindrome) adding two characters c and b.

For the second test case abcde cannot be transformed to palindrome using 3 insertions.

For the third test case ab can be transformed to cabac (which is palindrome) adding three characters a, c and c.

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

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

int Form_a_palindrome(string str,int len,int k)
{
    int i,j,max ;
    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] ;
        }
    }
    if(len-max<=k)
        return 1 ;
    return 0 ;
}

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