#include <stdio.h>
#include <stdlib.h>
// 文字列の長さを求める関数
int myStrlen(char s[]) {
int i;
for (i = 0; s[i] != '\0'; i++);
return i;
}
// 最短回文を作成する関数
char *setPalindrome(char s[]) {
int len = myStrlen(s);
int i, j;
// 最長回文前半部分を見つける
for (i = 0; i < len; i++) {
int is_palindrome = 1;
for (j = 0; j < len - i; j++) {
if (s[j] != s[len - i - 1 - j]) {
is_palindrome = 0;
break;
}
}
if (is_palindrome) {
break;
}
}
// 回文を格納するためのメモリ確保
char *tmp
= (char *)malloc((2 * len
- i
+ 1) * sizeof(char)); if (tmp == NULL) {
printf("Memory allocation failed\n"); }
// 文字列の前半部分をそのままコピー
for (j = 0; j < len; j++) {
tmp[j] = s[j];
}
// 後半部分を反転して追加
for (j = len - i - 1; j >= 0; j--) {
tmp[len + (len - i - 1 - j)] = s[j];
}
tmp[2 * len - i] = '\0'; // 終端文字を追加
return tmp;
}
int main() {
char nyuryoku[1024]; // 入力用の配列
char *kaibun; // 回文を受け取る
// 入力を取得
// 最短回文を生成
kaibun = setPalindrome(nyuryoku);
// 結果を表示
printf("%s\n -> %s\n", nyuryoku
, kaibun
);
// メモリの解放
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCi8vIOaWh+Wtl+WIl+OBrumVt+OBleOCkuaxguOCgeOCi+mWouaVsAppbnQgbXlTdHJsZW4oY2hhciBzW10pIHsKICAgIGludCBpOwogICAgZm9yIChpID0gMDsgc1tpXSAhPSAnXDAnOyBpKyspOwogICAgcmV0dXJuIGk7Cn0KCi8vIOacgOefreWbnuaWh+OCkuS9nOaIkOOBmeOCi+mWouaVsApjaGFyICpzZXRQYWxpbmRyb21lKGNoYXIgc1tdKSB7CiAgICBpbnQgbGVuID0gbXlTdHJsZW4ocyk7CiAgICBpbnQgaSwgajsKCiAgICAvLyDmnIDplbflm57mlofliY3ljYrpg6jliIbjgpLopovjgaTjgZHjgosKICAgIGZvciAoaSA9IDA7IGkgPCBsZW47IGkrKykgewogICAgICAgIGludCBpc19wYWxpbmRyb21lID0gMTsKICAgICAgICBmb3IgKGogPSAwOyBqIDwgbGVuIC0gaTsgaisrKSB7CiAgICAgICAgICAgIGlmIChzW2pdICE9IHNbbGVuIC0gaSAtIDEgLSBqXSkgewogICAgICAgICAgICAgICAgaXNfcGFsaW5kcm9tZSA9IDA7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBpZiAoaXNfcGFsaW5kcm9tZSkgewogICAgICAgICAgICBicmVhazsKICAgICAgICB9CiAgICB9CgogICAgLy8g5Zue5paH44KS5qC857SN44GZ44KL44Gf44KB44Gu44Oh44Oi44Oq56K65L+dCiAgICBjaGFyICp0bXAgPSAoY2hhciAqKW1hbGxvYygoMiAqIGxlbiAtIGkgKyAxKSAqIHNpemVvZihjaGFyKSk7CiAgICBpZiAodG1wID09IE5VTEwpIHsKICAgICAgICBwcmludGYoIk1lbW9yeSBhbGxvY2F0aW9uIGZhaWxlZFxuIik7CiAgICAgICAgZXhpdCgxKTsKICAgIH0KCiAgICAvLyDmloflrZfliJfjga7liY3ljYrpg6jliIbjgpLjgZ3jga7jgb7jgb7jgrPjg5Tjg7wKICAgIGZvciAoaiA9IDA7IGogPCBsZW47IGorKykgewogICAgICAgIHRtcFtqXSA9IHNbal07CiAgICB9CgogICAgLy8g5b6M5Y2K6YOo5YiG44KS5Y+N6Lui44GX44Gm6L+95YqgCiAgICBmb3IgKGogPSBsZW4gLSBpIC0gMTsgaiA+PSAwOyBqLS0pIHsKICAgICAgICB0bXBbbGVuICsgKGxlbiAtIGkgLSAxIC0gaildID0gc1tqXTsKICAgIH0KCiAgICB0bXBbMiAqIGxlbiAtIGldID0gJ1wwJzsgIC8vIOe1guerr+aWh+Wtl+OCkui/veWKoAoKICAgIHJldHVybiB0bXA7Cn0KCmludCBtYWluKCkgewogICAgY2hhciBueXVyeW9rdVsxMDI0XTsgIC8vIOWFpeWKm+eUqOOBrumFjeWIlwogICAgY2hhciAqa2FpYnVuOyAgICAgICAgIC8vIOWbnuaWh+OCkuWPl+OBkeWPluOCiwoKICAgIC8vIOWFpeWKm+OCkuWPluW+lwogICAgc2NhbmYoIiVzIiwgbnl1cnlva3UpOwogICAgCiAgICAvLyDmnIDnn63lm57mlofjgpLnlJ/miJAKICAgIGthaWJ1biA9IHNldFBhbGluZHJvbWUobnl1cnlva3UpOwogICAgCiAgICAvLyDntZDmnpzjgpLooajnpLoKICAgIHByaW50ZigiJXNcbiAgLT4gJXNcbiIsIG55dXJ5b2t1LCBrYWlidW4pOwoKICAgIC8vIOODoeODouODquOBruino+aUvgogICAgZnJlZShrYWlidW4pOwogICAgcmV0dXJuIDA7Cn0K