Shortest Palindromes

FJNU.1196

Description
A palindrome is a word that is the spelled the same forwards and backwards. ie, bab, and a are both palindromes, while ab is not.
Any word that is not already a palindrome can be made into one by attaching the appropriate letters. ab may not be a palindrome, but by attaching an a, we get aba which is a palindrome. Note that we could also attach ba to get abba which is also a palindrome. There are an infinite number of strings you can attach to get a palindrome. In this problem, we're interested in the shortest-length string that gives us the palindrome.

Input
Each line of input will have one word on it. The word will have no more than 30 characters. No spaces will appear on the line. The word consists solely of lower case alphabetic characters.

Output
For each line of input, print out the palindrome that comes from attaching the shortest length string of letters to the given word. Note that if the word is already a palindrome, then nothing should be added. Just print the word out again.

Sample Input
palin
a
ab
aba

Sample Output
palinilap
a
aba
aba

My Program

#include < iostream >
#include
< string .h >
#define  N 60
using   namespace  std;

int  main()
{
    
char str[N];
    
int n,i,j,k;
    
while(cin>>str)
    
{
        n
=strlen(str);
        j
=n-1;k=n-1;
        
for(i=0;i<n-1;i++)
            
if(str[n-1]==str[i])
            
{
                j
=0;
                
while(str[n-1-j]==str[i+j])
                    j
++;
                
if(i+j==n-1-j)
                
{
                    j
=-1;
                    
break;
                }

                j
=n-j;
                
if(k<j)
                    j
=k;
                
else
                    k
=j;
            }

        
if(j==-1)
            cout
<<str<<endl;
        
else
        
{
            cout
<<str;
            
for(i=j-1;i>=0;i--)
                cout
<<str[i];
            cout
<<endl;
        }

    }

    
return 0;
}

YOYO's Note: 
将最后一个数与前面数进行比较,找能符合的最大子串,把剩余的还没回文的子串倒序输出就好。
一个自己用来测试的数据:koshishifihs(貌似是这个……)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值