Computer Science, asked by brundhataani, 9 months ago

you are given a string which you have to convert into a palindrome such that each steps involves swapping two adjacent characters .Find the minimum nimber of steps it would take for you to do so
Note:1 .if the string could not be converted into a palindrome return -1
2.also,if the given string is a palindrome return 0​
(coding in C only)

#include<studio.h>
#include <string.h>
int swaps(char* input 1)

Answers

Answered by Ravispssbp
7

Answer:

you are given a string which you have to convert into a palindrome such that each steps involves swapping two adjacent characters .Find the minimum nimber of steps it would take for you to do so

Note:1 .if the string could not be converted into a palindrome return -1

2.also,if the given string is a palindrome return 0

you are given a string which you have to convert into a palindrome such that each steps involves swapping two adjacent characters .Find the minimum nimber of steps it would take for you to do so

Note:1 .if the string could not be converted into a palindrome return -1

2.also,if the given string is a palindrome return 0

Answered by ankhidassarma9
3

Answer:

#include <stdio.h>

#include <string.h>

void revstr(char *str)  

{  

   // declare variable  

   int i, l, temp;  

   l= strlen(str);  // using strlen()  we will get the length of  string  str

        for ( i = 0 ; i < l/2 ;  i++)  

   {  

       temp = str[i];  

       str[i] = str[l - i - 1] ;  

       str[l - i - 1] = temp;  

   }  

}  

int max(int n11, int n12)

{

   return (n11 > n12 ) ? n11 : n12;

}

void swap(char *str1, char *str2)

{

char *t = str1;

str1 = str2;

str2 = t;

}

int countSwap(char* s)

{

   char c=0;

int n = strlen(s);

int count = 0;

       int i , j;

for ( i= 0; i < n / 2; i++)

        {

 int le = i;

 int ri= n - le - 1;

 while (le < ri) {

  if (s[le] == s[ri]) {

   break;

  }

  else {

   ri--;

  }

 }

 if (le == ri) {

  return -1;

 }

 for (j = ri; j < n - le - 1; j++) {

  c = s[j];

           s[j] = s[j + 1];

           s[j + 1] = c;

  count++;

 }

}

return count;

}

int main()

{

   int ans1, ans2, c ;

char s[]  = "aabb";

    ans1 = countSwap(s);

revstr (s);

ans2 = countSwap(s);

c= max(ans1, ans2);

printf("% d",c);

return 0;

}

Explanation:

  • The above program will find  the minimum number of steps to convert a given String into a palindrome such that each steps involves swapping two adjacent characters .
  • If the string could not be converted into a palindrome , it will return -1.
Similar questions