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

本文介绍了一种算法,用于从给定字符串中找到最长的回文子串,并提供了详细的实现代码示例。

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

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
#include <bits/stdc++.h>
using namespace std;
int xd(char a[],int w,int i,int j)
{
    int u=0;
    while(j>i)//j即倒数字符要一直大于i即正数字符
    {
        if(a[i]==a[j]&&a[i+1]==a[j-1])//如果相等并且下一对也相等,则数目加2;否则不匹配数目归零
        {
            u=u+2;
        }
        else
        {
            u=0;
        }
        i=i+1;
        j=j-1;
    }
    if(i==j)//如果是回文串是奇数则数目加一,如果不是,则不加
    {
        u=u+1;
    }
    return u;
}
int main()
{
    int n,i,j,q,w,u,v;
    char a[51];
    while(gets(a))
    {
        i=0;
        u=0;
        w=strlen(a);
        j=w-1;
        for(i=0;i<w;i++)//循环比较开始字符和倒数字符
            for(j=w-1;j>=i;j--)
        {
            if(a[i]==a[j])//如果相等则进去函数
            {
                v=xd(a,w,i,j);
                if(v>u)
                    u=v;
            }
        }
        cout<<u<<endl;
    }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值