LeetCode 5:Longest Palindromic Substring

本文介绍了一种使用中心扩展法查找给定字符串中最长回文子串的有效算法。通过迭代每个字符作为潜在的回文中心,分别考虑奇数长度和偶数长度的回文情况,从而找到最长的回文子串。

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


分析:

采用中心扩展法,每个字符都有可能是回文字符串的中点。依次求得各字符作为中心的回文字符串,取其中最长的那个即可。

注意到回文字符串分为奇、偶两种类型对应“aba”和“aa”,所以每个字符都要求两次回文字符。

代码如下:

class Solution {
public:
    string str_helper(string s, int left, int right)
    {
        int n = s.length();
        while(left>=0 && right<=n-1 && s[left]==s[right]){
            left--;
            right++;
        }
        return s.substr(left+1, right-left-1);
        
    }
    string longestPalindrome(string s) {
            if(s.length() <= 1)
                return s;
        string longest = s.substr(0,1);
        for (int i=0; i<s.length(); i++){
            
            string tmp = str_helper(s, i, i);
            if (tmp.length() > longest.length())  {
                longest = tmp;
            }
            tmp = str_helper(s, i, i+1);
            if (tmp.length() > longest.length()) {
                longest = tmp;
            }
        }
    
        return longest;
    }

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值