class Solution {
public String longestPalindrome(String s) {
String t="$"; //防止越界
for(int i=0;i<s.length();i++) {
t+="#"+s.charAt(i);
}
t+="#@";
//index为最长回文子串中心,maxlength为其长度
//rigth为当前回文子串右边届,centre为中心
int index=0,maxlength=0,rigth=0,centre=0;
int n=t.length();
int[] p=new int[n];
for(int j=1;j<n-1;j++) {
p[j]=rigth>j?Math.min(p[2*centre-j],rigth-j):1;
while(t.charAt(j+p[j])==t.charAt(j-p[j])) {
p[j]++;
}
if(rigth<j+p[j]) {
rigth=j+p[j];
centre=j;
}
if(maxlength<p[j]-1) {
index=j;
maxlength=p[j]-1;
}
}
//找到原字符串最大回文串的初始索引
int start=(index-maxlength)/2;
return s.substring(start,start+maxlength);
}
}
Leetcode--5、manacher算法
猜你喜欢
转载自blog.csdn.net/qq_44158395/article/details/105304903
今日推荐
周排行