A palindrome is a word that reads the same backward and forw

A palindrome is a word that reads the same backward and forward. Given a string S, you are allowed to convert it to a palindrome by adding 0 or more characters in front of it. Find the length of the shortest palindrome that you can create from S by applying the above transformation. Your program will take A string S (1 lessthanorequalto Length(S) lessthanorequalto 100) where each character of S will be a lowercase alphabet (Between \'a\' to \'z\') For each input, print out an integer L denoting the length of the shortest palindrome you can generate from S. baaa 7 The shortest palindrome you can construct from \'baaa\' is \'aaabaaa\'.

Solution

// A Naive recursive program to find minimum number insertions
// needed to make a string palindrome
#include <stdio.h>
#include <string.h>
// retruns the length of given string.
int len(char str[]){
   int i;
   for(i=0;str[i]!=\'\\0\';++i);
   return i;
}
// returns 1 if given string is palindrome, else 0.
int checkPalindrome(char str[]){
   int l = len(str)-1;
   int i=0;
   while(i<=l){
       if(str[i]==str[l]){
           i++;
           l--;
       }
       else
           return 0;
   }
   return 1;
}
int toPalindrome(char str[]){
   int l = len(str);
   if(checkPalindrome(str))
       return l;
   char palin[l];        
   int ind = 0;
   while(ind<l){
       char check[l*2];
       palin[ind] = str[ind+1]; // add chars to palin
       int i,j,k=0;
       for(i=ind;i>=0;i--,k++){        // add chars to check
           check[k] = palin[i];
       }
      
       for(j=0;j<l;j++,k++){
           check[k] = str[j];
       }
       if(checkPalindrome(check)){         // find whether check is palindrome.
           return len(check);
       }
       ind++;
   }
   return 1;
}


// Driver program to test above functions
int main()
{
//   setvbuf(stdout, NULL, _IONBF, 0);
    char str[] = \"baaa\";
    printf(\"%d\ \",toPalindrome(str));
    return 0;
}

/* sample output

7

*/

 A palindrome is a word that reads the same backward and forward. Given a string S, you are allowed to convert it to a palindrome by adding 0 or more characters
 A palindrome is a word that reads the same backward and forward. Given a string S, you are allowed to convert it to a palindrome by adding 0 or more characters

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site