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.

Example:
Input: “babad”

Output: “bab”

Note: “aba” is also a valid answer.

Example:
Input: “cbbd”

Output: “bb”

解决代码:

class Solution {
public:
    string longestPalindrome(string s) {
        int N=s.size()+1;
        int p[N<<1];
        string t = "$";
        for (char ch : s) {
            t += '#';
            t += ch;
        }
        t += '#';
        // t为处理过的字符串,p为记录长度的数组  
        memset(p, 0, sizeof(p));  
        // mx为已判断回文串最右边位置,id为中间位置,mmax记录p数组中最大值  
        int mx = 0, id = 0, mmax = 0;  
        int len = t.length();
        int right = 0;
        for (int i = 1; i < len; i++) {  
            p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;  
            while (t[i + p[i]] == t[i - p[i]])  
                p[i]++;  
            if (i + p[i] > mx) {  
                mx = i + p[i];  
                id = i;  
            }  
            if (mmax < p[i]) {
                mmax = p[i]; 
                right = i;
            }
        }  
        // 最长为mmax - 1  
        return s.substr(right/2 - mmax/2, mmax-1);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值