## 一、动态规划

``````public String longestPalindrome(String s) {
int n = s.length();
if(n==0){
return "";
}
boolean[][] isPalidrome = new boolean[n][n];
int max = 1;
int start = 0;
int end = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j)
isPalidrome[i][j] = true;
}
}
for (int i = 0; i < n - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
isPalidrome[i][i + 1] = true;
}
}
for (int i = n - 2; i >= 0; i--) {
for (int j = n - 1; j > i; j--) {
if (j > i + 1) {
isPalidrome[i][j] = isPalidrome[i + 1][j - 1] && (s.charAt(i) == s.charAt(j));
}
if (max < j - i + 1 && isPalidrome[i][j]) {
start = i;
end = j;
max = j - i + 1;
}
}
}
return s.substring(start, end + 1);
}
``````

## 二、中心扩展算法

``````public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start + 1) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
``````

## 三、Manacher 算法

``````public String longestPalindrome(String s) {
if(s.length()==0){
return "";
}
StringBuilder sb=new StringBuilder();
sb.append(' ');
for(int i=0;i<s.length();i++){
sb.append(s.charAt(i));
sb.append(' ');
}
s=sb.toString();
int len=s.length();
//右边界
int rightSide=0;
//右边界对应的回文串中心
int rightSideCenter=0;
//保存每个字符为中心的回文长度一半（向下取整）
int[] halfLenArr=new int[len];
//记录回文中心
int center=0;
//记录最长回文长度
int longestHalf=0;
for(int i=0;i<len;i++){
//是否需要中心扩展
boolean needCalc=true;
if(rightSide>i){
//计算相对rightSideCenter的对称位置
int leftCenter=2*rightSideCenter-i;
halfLenArr[i]=halfLenArr[leftCenter];
if (i+halfLenArr[i]>=rightSide){
halfLenArr[i]=rightSide-i;
}
if(i+halfLenArr[leftCenter]<rightSide){
needCalc=false;
}
}
if(needCalc){
while(i-1-halfLenArr[i]>=0&&i+1+halfLenArr[i]<len){
if(s.charAt(i+1+halfLenArr[i])==s.charAt(i-1-halfLenArr[i])){
halfLenArr[i]++;
}else{
break;
}
}
rightSide=i+halfLenArr[i];
rightSideCenter=i;
if(halfLenArr[i]>longestHalf){
center=i;
longestHalf=halfLenArr[i];
}
}
}
StringBuilder str=new StringBuilder();
for(int i=center-longestHalf+1;i<=center+longestHalf;i+=2){
str.append(s.charAt(i));
}
return str.toString();
}
``````

0条评论