fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int myStrlen(char s[]){
  5. int i;
  6. for(i=0; s[i] != '\0'; i++);
  7. return i;
  8. }
  9.  
  10. // 部分文字列が回文かどうかを判定
  11. int isPalindrome(char s[], int start, int end){
  12. while(start < end){
  13. if(s[start] != s[end]) return 0;
  14. start++;
  15. end--;
  16. }
  17. return 1;
  18. }
  19.  
  20. char *setPalindrome(char s[]){
  21. int len = myStrlen(s);
  22. int addIndex = 0;
  23.  
  24. for(int i = 0; i < len; i++){
  25. if(isPalindrome(s, i, len-1)){
  26. addIndex = i;
  27. break;
  28. }
  29. }
  30.  
  31. int addLen = addIndex;
  32. int newLen = len + addLen;
  33.  
  34. char *tmp = (char *)malloc((newLen + 1) * sizeof(char));
  35. if(tmp == NULL){
  36. printf("Memory allocation failed\n");
  37. exit(1);
  38. }
  39.  
  40. for(int i = 0; i < len; i++){
  41. tmp[i] = s[i];
  42. }
  43.  
  44. for(int i = 0; i < addLen; i++){
  45. tmp[len + i] = s[addIndex - 1 - i];
  46. }
  47.  
  48. tmp[newLen] = '\0';
  49. return tmp;
  50. }
  51.  
  52. int main(){
  53. char nyuryoku[1024];
  54. char *kaibun;
  55. scanf("%s", nyuryoku);
  56. kaibun = setPalindrome(nyuryoku);
  57. printf("%s\n -> %s\n", nyuryoku, kaibun);
  58. free(kaibun);
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5316KB
stdin
abab
stdout
abab
  -> ababa