1. 题目:
给你一个字符串 s
,找到 s
中最长的回文子串。
2. 示例:
输入:s = "babad"
输出:"bab" 解释:"aba" 同样是符合题意的答案。
3. Code
public class LongestPalindrome {
int start = 0, maxLen = 1;
public String longestPalindrome(String s) {
/**
* @Method: longestPalindrome
* @Author: haifwu
* @Version: 1.0
* @Date: 21/05/2021 20:51
* @param s
* @Return: java.lang.String
* @Description: 中央扩散
*/
if (s == null || s.length() == 0) {
return "";
}
for (int i = 0; i < s.length(); i++) {
extendPalindrome(s, i, i);
extendPalindrome(s, i, i + 1);
}
return s.substring(start, start + maxLen);
}
public void extendPalindrome(String s, int left, int right) {
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
if(maxLen < right - left - 1) {
start = left + 1;
maxLen = right - left - 1;
}
}
public static void main(String[] args) {
String s = "babad";
System.out.println(new LongestPalindrome().longestPalindrome(s));
}
}