fjnu 1196 Shortest Palindromes

本文介绍了一种构造最短回文串的方法,通过检查给定字符串是否为回文,并在非回文的情况下找到需要附加的最短字符序列来形成回文。文中提供了一个具体的实现示例。

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

 

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
KEY:构造最短回文,先判断,要是不是回文就进行构造,将原有的字符串反向,与原来的字符串末尾比较,要最大的匹配;
Source:

#include
<iostream>
using namespace std;

int isPalindromes(char str[35])
{
    
int len=strlen(str);
    
int i=0,j=len-1;
    
while(i<j)
    
{
        
if(str[i]!=str[j]) return 0;
        i
++;
        j
--;
    }

    
return 1;
}


char* translate(char str[])
{
    
char c;
    
int len=strlen(str);
    
int i=0,j=len-1;
    
while(i<j)
    
{
        c
=str[i];
        str[i]
=str[j];
        str[j]
=c;
        i
++;
        j
--;
    }

    
return str;
}


void shortest(char str[])
{
    
char tmp[35];
    strcpy(tmp,str);
    strcpy(tmp,translate(tmp));
    
int i=0,j=0,k;
    
int len=strlen(str);
    
while(i<len)
    
{
        
if(str[i]==tmp[j])
        
{
            i
++;
            j
++;
        }

        
else
        
{
            i
=i-j+1;
            j
=0;
        }

    }

    
for(k=i,i=0;i<k;i++)
        cout
<<str[i];
    
for(;j<len;j++)
        cout
<<tmp[j];
    cout
<<endl;
}


int main()

//    freopen("fjnu_1196.in","r",stdin);
    char str[35];
    
while(gets(str))
    
{
        
if(isPalindromes(str))
            cout
<<str<<endl;
        
else 
            shortest(str);
    }

    
return 0;
}




    






 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值