PAT 1040 Longest Symmetric String 双指针

题目:

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

题解:

#include <bits/stdc++.h>

bool is_symmetric(std::string& s, int start, int end) {
    std::string str = s.substr(start, end - start + 1);
    int left = 0, right = str.size() - 1;
    while (left <= right) {
        if (str[left++] != str[right--]) {
            return false;
        }
    }
    return true;
}

int main() {
    std::string str;
    std::getline(std::cin, str);

    int result = 0;

    for (int i = 0; i < str.length(); i++) {
        for(int j = i; j < str.length(); j++) {
            bool flag = is_symmetric(str, i, j);
            if (flag) {
                result = std::max(result, j - i + 1);
            }
        }
    }


    std::cout << result << std::endl;

    return 0;
}

### 滑动窗口算法双指针算法的关系 滑动窗口实际上是一种基于双指针技术的应用形式,主要用于处理数组或列表中的连续子序列问题。这类方法的核心在于维护一个动态调整大小的窗口,该窗口由一对指向不同位置的指针界定[^1]。 #### 双指针特性 双指针通常指的是在同一数据结构内设置两个索引来遍历元素的方法。这两个指针可以在相同方向上前进(如同向双指针),也可以朝相反的方向移动(如相向双指针)。这种方法有助于减少嵌套循环带来的额外开销,从而提升性能效率[^2]。 #### 滑动窗口特点 当提到滑动窗口时,重点放在如何有效地管理这个“窗口”,即左右边界之间的部分。随着右端点逐步扩展以探索新的可能性,左端点则根据特定条件收缩来保持最优解的有效性。这使得滑动窗口特别适合用于寻找满足某些约束条件下最小子串等问题。 ```python def length_of_longest_substring(s: str) -> int: char_map = {} left, max_length = 0, 0 for right in range(len(s)): if s[right] in char_map: left = max(char_map[s[right]] + 1, left) char_map[s[right]] = right max_length = max(max_length, right - left + 1) return max_length ``` 此代码片段展示了利用哈希表配合滑动窗口机制计算给定字符串中最长不含重复字符子串长度的过程。 #### 联系与差异 尽管两者都依赖于双指针的概念,但主要区别在于关注焦点的不同: - **双指针** 更侧重于通过两者的相对运动直接解决问题; - **滑动窗口** 则强调对区间内部状态变化的关注,并且往往伴随着更复杂的逻辑判断以便维持最佳解决方案的状态[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

polarours

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值