Shortest Palindromes

来源:互联网 发布:英国病人小说知乎 编辑:程序博客网 时间:2024/05/24 04:47

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(貌似是这个……)

原创粉丝点击