leetcode题解5-Longest Palindromic Substring

本文介绍了一种求解字符串中最长回文子串的方法,通过遍历字符串并以每个字符为中心来查找最长的回文串,实现了O(n^2)的时间复杂度。此外还提到了更高效的Manacher算法,该算法能够将时间复杂度降低到O(n)。

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

题目:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"


思路:遍历字符串,计算以当前字符为“中心”的最长对偶串。算法复杂度O(n^2)。

针对此问题有专门的算法-manacher算法,可以实现O(n)复杂度,但是思路还未搞透彻。


代码:

class Solution {
public:
    string longestPalindrome(string s) {
        // O(n^2) 顺序遍历s,以遍历字符为中心双向增长。
        string res;  
        for(int i = 0; i < s.size(); i++){            
            string temp1,temp2; 
            temp1= getPalString(s,i,i);   // 考虑奇数情况 'aba'
            if(temp1.size() > res.size()) res = temp1;
            temp2 = getPalString(s,i,i+1);    // 偶数情况 'abba'
            if(temp2.size() > res.size()) res = temp2;
        }
        return res;
        
    }
    // 函数计算以l,r展开得到的最长对偶串
    string getPalString(string s, int l, int r){
        while(l>=0 && r<s.size() && s[l] == s[r]){
            l--; r++; 
        }
        return s.substr(l+1,r-1-l);   // 返回对偶子串     
    }
};

python


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值