「1040」Longest Symmetric String

本文探讨如何通过遍历可能的对称中心点,利用C++编程解决给定字符串中找到最长对称子串的问题。方法涉及检查中心点两侧字符的相等性,并记录最长对称子串的长度。适合初学者理解对称字符串匹配算法。

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

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11

Ω

输出最长对称子串的长度,简洁明了,跟这篇博客一样,我喜欢。

对于对称字符串我们可以根据对称中心点去寻找,而中心点可能是字符(奇对称)也可能是两个字符中间(偶对称),那么中心点共有种选择。然后计算中心点周围两个邻近字符的索引,循环找出最长对称子串。


C ☺ D E

#include <iostream>

using namespace std;

int main()
{
    string s;
    getline(cin, s);
    int max = 1;
    for (int i = 0; i < 2 * s.size(); ++i)
    {
        int left = i / 2, right = (i + i % 2) / 2 + 1, sum = i % 2;
        while (left >= 0 && right < s.size())
        {
            if (s[left--] == s[right++])
                sum += 2;
            else
                break;
        }
        if (sum > max)
            max = sum;
    }
    cout << max;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值