「1040」Longest Symmetric String

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

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;
}
### 使用 `itertools.zip_longest` 函数 Python 的 `itertools` 模块提供了多种用于高效循环操作的迭代器工具。其中,`zip_longest` 是一个非常有用的函数,它允许两个或多个可迭代对象并行遍历,并在最短序列耗尽之后继续填充指定值。 #### 基本语法 ```python import itertools result = itertools.zip_longest(iterable1, iterable2, fillvalue=None) ``` 此方法接受任意数量的可迭代参数以及一个名为 `fillvalue` 的关键字参数,默认情况下该参数设置为 `None`[^1]。 当输入的可迭代对象长度不一致时,较短的对象会用 `fillvalue` 来补充缺失的位置直到最长的那个结束为止。 #### 实际应用案例 考虑如下场景:有两个列表分别代表不同月份销售量的数据集A和B,但是数据集中某些月可能缺少记录,在这种情况下就可以利用 `zip_longest` 进行处理: ```python from itertools import zip_longest sales_A = ['Jan', 'Feb', 'Mar'] sales_B = [100, 200] for month, sale in zip_longest(sales_A, sales_B, fillvalue=0): print(f"{month}: {sale}") ``` 上述代码将会输出: ``` Jan: 100 Feb: 200 Mar: 0 ``` 这里可以看到三月份并没有实际销售额数值,因此被替换成了默认填充值 `0`。 #### 多个可迭代对象的情况 如果需要同时处理三个以上的可迭代对象,则同样适用: ```python list_a = ["a", "b"] list_b = [1, 2, 3] list_c = ["x", "y", "z"] combined = list(zip_longest(list_a, list_b, list_c)) print(combined) # 输出结果将是 [('a', 1, 'x'), ('b', 2, 'y'), (None, 3, 'z')] ``` 在这个例子中,由于第一个列表只有两项而其他两个各有三项,所以最后一项将由 `None` 补齐以匹配最长序列的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值