LeetCode 5 : Longest Palindromic Substring ---- 最长回文

原题链接: https://leetcode.com/problems/longest-palindromic-substring/


一:原题内容

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


二:分析理解

详情见   Manacher算法--O(n)求得最长回文


三:AC代码

class Solution 
{
public:
    string longestPalindrome(string s) 
    {
        int len=s.size();
        char ch[2005];
        int p[2005]={0};
        ch[0]='$';
        ch[1]='#';
        int j=2;
        for(int i=0;i<len;i++)
        {
            ch[j++]=s[i];
            ch[j++]='#';
        }
        ch[j]='\0';
        len=j;
        
        int mx=0;
        int id;
        int maxLen=0;
        int maxId;
        for(int i=0;i<len;i++)
        {
            if(i<mx)
                p[i]=min(p[2*id-i],mx-i);
            else
                p[i]=1;
            
            while(ch[i-p[i]]==ch[i+p[i]])
                p[i]++;
            
            if(mx<i+p[i])
            {
                mx=i+p[i];
                id=i;
            }
            
            if(p[i]>maxLen)
            {
                maxLen=p[i]-1;
                maxId=i;
            }
        }
    
        int prePos=maxId-maxLen+1;
        int pos=prePos/2-1;
        
        return s.substr(pos,maxLen);
    }
};

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        
        t="$#"+"#".join(s)+"#_"
        p=[0]*2500
        maxLeft,id,maxLen,mx=0,0,0,0
        
        for i in range(1,len(t)-1):
            if i<mx:
                p[i]=min(p[2*id-i],mx-i)
            else:
                p[i]=1
             
            while t[i-p[i]]==t[i+p[i]]:
                p[i]+=1
        
            if p[i]-1>maxLen:
                maxLen=p[i]-1
                maxLeft=i-p[i]+1
        
            if i+p[i]>mx:
                mx=i+p[i]
                id=i
        
        if maxLeft%2!=0:
            maxLeft+=1
        
        k=maxLeft/2-1
        return s[k:k+maxLen]




返回LeetCode 题解目录





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值