## 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 最长回文子字符串 两种方法分析解答

2013-11-23 10:27:57

#### LeetCode(5) Longest Palindromic Substring

2013-11-27 14:00:30

#### LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)

2015-05-06 15:38:22

#### [LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)

2015-02-28 00:09:45

#### LeetCode5——Longest Palindromic Substring 最易懂的解法

2016-01-22 23:05:18

#### [LeetCode][5]Longest Palindromic Substring解析 -Java实现

2016-06-05 13:48:00

#### [LeetCode]5 Longest Palindromic Substring(C++，Python实现)

2014-05-23 21:28:36

#### LeetCode第五题，Longest Palindromic Substring

2014-08-05 14:29:41

#### leetcode 5 Longest Palindromic Substring--最长回文字符串

2016-08-29 00:22:17

#### Leetcode 5. Longest Palindromic Substring 新补充Manacher算法

2016-03-15 09:34:45

## 不良信息举报

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