2017上海金马五校程序设计竞赛 E:Find Palindrome

Time Limit: 1 s

Description

Given a string  S, which consists of lowercase characters, you need to find the longest palindromic sub-string.

A sub-string of a string  S   is another string  S'   that occurs "in"  S . For example, "abst" is a sub-string of "abaabsta". A palindrome is a sequence of characters which reads the same backward as forward.

 

Input

There are several test cases.
Each test case consists of one line with a single string  S (1 ≤ | | ≤ 50).

 

Output

For each test case, output the length of the longest palindromic sub-string.

 

Sample Input

 
 
sasadasa
bxabx
zhuyuan

 

Sample Output

7
1
3

题目意思:

给你一串字符,让你找出其中最长的回文子串长度。

解题思路:

首先先看字符串,对于第 i 个字符str[i],如果回文子串有奇数个字符,那么以 i 为中心向左向右扩展,直到发现对称位置字符不相等,如果扫过X个字符,那么回文子串长度为2*X+1.

如果回文子串有偶数个字符,对于第 i 个字符str[i]在最接近对称轴的左边。对于这种情况我们要从第 i 个位置开始扫描,并与第 i+1 个位置字符进行比较,在向左向右扩展,直到对称位置字符不相同为止。如果扫过了X个字符,那么回文子串长度为2*X。



#include<iostream>  
#include<stdio.h>  
#include<algorithm>  
#include<string.h>  
#define INF 999999  
using namespace std;     
int main()  
{  
    int maxlen,i,j,len;   ///最长对称子串长度。  
    char str[1003];  
    while(gets(str))  
    {  
        maxlen = 0;  
        len = strlen(str);  
        for(i = 0; i < len; i++)  
        {  
            ///考虑是i是奇数串的中心,以i为中心,同时往左往右扩展  
            for(j = 0; i-j>=0&&i+j<=len; j++)  
            {  
                if(str[i-j]!=str[i+j])  
                    break;  
                if(2*j+1>maxlen)  
                    maxlen = 2*j+1;  
            }  
            ///i是偶数串的中心  
            for(j = 0; i-j>=0&&i+j+1<len;j++)  
            {  
                if(str[i-j]!=str[i+j+1])  
                    break;  
                if(2*j+2>maxlen)  
                    maxlen = 2*j+2;  
            }  
        }  
        printf("%d\n",maxlen);  
    }  
    return 0;  
}  


  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值