# Leetcode Longest Palindromic Substring（最长回文字串）

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

### 1 动态规划（DP solution） O(n^2)

P[i,j] = 字符串区间[i,j]是否为palindrome.

S = a b c c b
Index = 0 1 2 3 4

P[0,0] = 1
P[0,1] = S[0] == S[1]  , P[1,1] =1
P[0,2] = S[0] == S[2] && P[1,1], P[1,2] = S[1] == S[2] ,  P[2,2] = 1
P[0,3] = S[0] == S[3] && P[1,2], P[1,3] = S[1] == S[3] && P[2,2] , P[2,3] =S[2] ==S[3],  P[3,3]=1     

………………….

P[i,j] = 1  if i ==j
P[i,j] = S[i] ==S[j]   if j = i+1
P[i,j] = S[i] == S[j] && P[i+1][j-1]  if j>i+1

JAVA实现如下：

private String longestPalindrome(String s) {
int len = s.length();
boolean[][] p = new boolean[len][len];
int maxLength = 0, start = 0, end = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j < i; j++) {
p[j][i] = (s.charAt(j) == s.charAt(i) && (i - j < 2 || p[j + 1][i - 1]));
if (maxLength < (i - j + 1)) {
maxLength = i - j + 1;
start = j;
end = i;
}
}
p[i][i] = true;
}
return s.substring(start, end);
}

### 2 Manacher’s ALGORITHM: O(n)

int n=str.length();
for(int i=0;i<n;i++){
sb.append("#").append(str.charAt(i));
}
sb.append("#");
return sb.toString();
}
public String longestPalindrome(String s){
String newStr=getManacherString(s);
int len=newStr.length();
int end=0;
int index=0;
int maxLen=0;
int maxIndex=0;
for(int i=1;i<len;i++){
if(end>i){
}else{
}
}else{
break;
}
}
index=i;
}
maxIndex=i;
}
}
StringBuilder sb=new StringBuilder();
for(int i=maxIndex-maxLen+1;i<maxIndex;i++){
if(newStr.charAt(i)!='#'){
sb.append(newStr.charAt(i));
}
}
String resultStr=sb.toString();
if(newStr.charAt(maxIndex)!='#'){
resultStr+=newStr.charAt(maxIndex);
}
resultStr+=sb.reverse().toString();
return resultStr;
}

}

github地址 LongestPalindromic

• 本文已收录于以下专栏：

举报原因： 您举报文章：Leetcode Longest Palindromic Substring（最长回文字串） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)