LeetCode - 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.

分析:

先把字符串每两个字符之间都放上#,这样可以把所有回文子串都变成奇数长度。

存一下当前延展到最右边的回文子串的信息。判断以i点为中心的回文子串有多长的时候就可以利用当前延展到最右边的子串的对称信息。

class Solution {
public:
    string convert(string s)
    {
        string ans="^";
        for(auto ch:s)
        {
            ans += "#";
            ans += ch;
        }
        ans+="#%";
        return ans;
    }
    string longestPalindrome(string s) {
        if(s.empty())return s;
        string tmps = s;
        s = convert(s);
        int n = s.length();
        int center = 0, right = 0;
        int *p = (int*)calloc(n,sizeof(int));
        for(int i = 1; i < n-1; i++)
        {
            int j = 2*center - i;
            p[i] = right > i? min(right - i, p[j]):1;
            while(s[i+p[i]] == s[i-p[i]])
                p[i]++;
            if(i+p[i]-1 > right)
            {
                center = i;
                right = i+p[i]-1;
            }
        }
        int ans = 0, ansi = 0;;
        for(int i = 1;i < n-1; i++)
        {
            if(p[i]>ans)
            {
                ans = p[i];
                ansi = i;
            }
        }
        free(p);
        return tmps.substr((ansi - (ans-1) -1) / 2, ans - 1);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值