• 2017年上海金马五校程序设计竞赛:Problem E : Find Palindrome (字符串处理)


    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 ≤ |S | ≤ 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。加上的1就是加上i本身。如下图所示:

    由第 i 个字符a[i]构成回文偶数串。i在最接近对称轴的左侧。

    代码:

    #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
    ",maxlen);
        }
        return 0;
    }
  • 相关阅读:
    Hystrix解析(三)
    Hystrix解析(二)
    在阿里云开发平台编写第一个 HelloWorld 程序
    Jenkins与Docker的自动化CI/CD实战
    网页计数器例子
    ServletContext 对象
    Session
    Cookie
    Request 对象作用域
    转发,重定向(包括请求中文乱码解决)
  • 原文地址:https://www.cnblogs.com/cmmdc/p/6941185.html
Copyright © 2020-2023  润新知