#### 题目描述
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
#### 示例
```txt
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
```
```txt
输入: "cbbd"
输出: "bb"
```
#### 思路
回文字符串就是从左读和从右读都是相同的,例如:“上海自来水来自海上”,所以可以将其看成左右对称的字符串。首先需要明确的是连续相同的字符肯定是回文子串,所以第一步是找到与当前索引位置上的字符不相同的字符,然后同时向左和向右延伸(延伸的条件是对称位置上的字符相同),从而找到回文字子串。之后通过循环的方式找到最长回文子串。
#### 代码
```java
/**
* @author miantiao
* @time 2020年2月22日 下午12:20:22
*/
public class LongestPalindromicSubstring {
public static String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
int[] indexs = new int[2];//保存最长回文字符串在原串中的起始索引位置
char[] chars = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
i = findDiffChar(chars, i, indexs);//找到下一个与当前字符不同的字符
}
return s.substring(indexs[0], indexs[1] + 1);
}
public static int findDiffChar(char[] chars, int low, int[] indexs) {
//查找中间相同部分
int high = low;
while (high < chars.length - 1 && chars[high + 1] == chars[low]) {
high++;
}
int lastSameChar = high;//记录中间相同部分最后一个字符
//从中间向左右延伸,查找回文字符串
while (low > 0 && high < chars.length - 1 && chars[low - 1] == chars[high + 1]) {
low--;
high++;
}
//记录最大回文字符串长度
if (high - low > indexs[1] - indexs[0]) {
indexs[0] = low;
indexs[1] = high;
}
return lastSameChar;
}
}
```

最长回文子串