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

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.


Example:

Input: "cbbd"

Output: "bb"

class Solution {
public String longestPalindrome(String s) {
if (s.length() <= 1) {
return s;
}
int left, right;
String res = s.substring(0, 1);
for (int i = 0; i < s.length(); i++) {
left = right = i;
while (left > -1 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
if (right - left - 1 > res.length()) {
res = s.substring(left + 1, right);
}
}

for (int i = 0; i < s.length() - 1; i++) {
left = i;
right = i + 1;
while (left > -1 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
if (right - left - 1 > res.length()) {
res = s.substring(left + 1, right);
}
}

return res;
}
}

class Solution {
public String longestPalindrome(String s) {
int sLen = s.length();
if (sLen <= 1) {
return s;
}
boolean[][] isPalindrome = new boolean[sLen][sLen];
// 初始化，i=j时只有一个字符，是回文字符串。i>j时是空串，也视为回文字符串。i<j时先默认初始化为false。
for (int i = 0; i < sLen; i++) {
for (int j = 0; j < sLen; j++) {
if (i < j) {
isPalindrome[i][j] = false;
} else {
isPalindrome[i][j] = true;
}
}
}
int left = 0, right = 0;
for (int step = 1; step < sLen; step++) {
for (int i = 0; i + step < sLen; i++) {
int j = i + step;
if (s.charAt(i) != s.charAt(j)) {
isPalindrome[i][j] = false;
} else {
isPalindrome[i][j] = isPalindrome[i + 1][j - 1];
if (isPalindrome[i][j] == true) {
if (j - i > right - left) {
left = i;
right = j;
}
}
}

}
}
return s.substring(left, right + 1);
}
}