NOJ [1148] Creating Palindrome

本文介绍了一种算法,该算法能够判断一个给定的字符串是否可以被重新排列成一个回文串,并输出字典序最小的可能结果。如果无法形成回文串,则输出0。文章通过一个具体的C语言实现案例展示了如何计数每个字符出现的次数,并根据这些信息决定字符串是否能转换为回文串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 问题描述
  • XadillaX likes to play with strings very much.
    His favorite string is palindrome. Once he come across with a string, XadillaX always wants to change it to a palindrome by resorting the letters.

    Now give you a string, you should tell him whether the string can be changed to a palindrome. If yes, you should output it. (The smallest one in Lexicographic order)

  • 输入
  • This problem contains several cases.
    Each case is a string, no longer than 20000. Only contains uppercase letters.
  • 输出
  • For each case, if it can be changed to a palindrome, output it. If can't, output 0.


    本题有点水。。。就不解释了

    #include<stdio.h>
    #include<string.h>

    int str[100];
    char letter[20010];
    char palindrome[20010];
    int main()
    {
    while(~scanf("%s",letter))
    {
    int i,j,len=strlen(letter);
    memset(str,0,sizeof(str));
    for (i = 0; i < len; ++i)
    str[letter[i]]++;
    int odd=0;
    for(i=65;i<=90;i++)
    {
    if(str[i]%2)
    odd++;
    if(odd>=2)
    break;
    }
    if(odd>=2)
    printf("0\n");
    else
    {
    int s=0,t=len-1;
    for(i=65;i<=90;i++)
    {
    if(str[i]%2==0 && str[i])//偶数个 且不为0
    {
    while(str[i])
    {
    palindrome[s]=(char)i;
    s++;
    palindrome[t]=(char)i;
    t--;
    str[i]-=2;
    }
    }
    else if(str[i]%2)
    {
    palindrome[len/2]=(char)i;
    for(j=0;j<str[i]-1;j+=2)
    {
    palindrome[s]=(char)i;
    s++;
    palindrome[t]=(char)i;
    t--;
    }
    }
    }
    palindrome[len]='\0';
    printf("%s\n",palindrome );
    }
    }
    return 0;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值