0
点赞
收藏
分享

微信扫一扫

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 题解目录​​





举报

相关推荐

0 条评论