We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<assert.h>#include<ctype.h>#include<limits.h>#include<math.h>#include<stdbool.h>#include<stddef.h>#include<stdint.h>#include<stdio.h>#include<stdlib.h>#include<string.h>char*readline();char*ltrim(char*);char*rtrim(char*);intparse_int(char*);/* * Complete the 'solve' function below. * * The function is expected to return a DOUBLE. * The function accepts STRING s as parameter. */boolis_palindrome(constchar*s){intn=strlen(s);for(inti=0;i<n/2;++i){if(s[i]!=s[n-i-1]){returnfalse;}}returntrue;}intmin_swaps_to_palindrome(char*s){intn=strlen(s);intswaps=0;for(inti=0;i<n/2;++i){intleft=i;intright=n-left-1;while(left<right&&s[left]!=s[right]){right--;}if(left==right){if(n%2==1){for(intj=right;j<n-left-1;++j){chartemp=s[j];s[j]=s[j+1];s[j+1]=temp;swaps++;}continue;}else{return-1;}}else{for(intj=right;j<n-left-1;++j){chartemp=s[j];s[j]=s[j+1];s[j+1]=temp;swaps++;}}}returnswaps;}doublesolve(char*s){if(is_palindrome(s)){return0.0;}intmin_swaps=min_swaps_to_palindrome(s);if(min_swaps==-1){return(double)INT_MAX;}return(double)min_swaps;}intmain(){FILE*fptr=fopen(getenv("OUTPUT_PATH"),"w");intt=parse_int(ltrim(rtrim(readline())));for(intt_itr=0;t_itr<t;t_itr++){char*s=readline();doubleresult=solve(s);fprintf(fptr,"%lf\n",result);}fclose(fptr);return0;}char*readline(){size_talloc_length=1024;size_tdata_length=0;char*data=malloc(alloc_length);while(true){char*cursor=data+data_length;char*line=fgets(cursor,alloc_length-data_length,stdin);if(!line){break;}data_length+=strlen(cursor);if(data_length<alloc_length-1||data[data_length-1]=='\n'){break;}alloc_length<<=1;data=realloc(data,alloc_length);if(!data){data='\0';break;}}if(data[data_length-1]=='\n'){data[data_length-1]='\0';data=realloc(data,data_length);if(!data){data='\0';}}else{data=realloc(data,data_length+1);if(!data){data='\0';}else{data[data_length]='\0';}}returndata;}char*ltrim(char*str){if(!str){return'\0';}if(!*str){returnstr;}while(*str!='\0'&&isspace(*str)){str++;}returnstr;}char*rtrim(char*str){if(!str){return'\0';}if(!*str){returnstr;}char*end=str+strlen(str)-1;while(end>=str&&isspace(*end)){end--;}*(end+1)='\0';returnstr;}intparse_int(char*str){char*endptr;intvalue=strtol(str,&endptr,10);if(endptr==str||*endptr!='\0'){exit(EXIT_FAILURE);}returnvalue;}
Where is the issue???
w
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Palindromes
You are viewing a single comment's thread. Return to all comments →
Where is the issue???
w