# 最长回文子串
- 最长回文子串
来源:力扣(LeetCode) 链接 (opens new window):https://leetcode.cn/problems/longest-palindromic-substring/ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# 问题
给你一个字符串 s,找到 s 中最长的回文子串
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
# 思路
中心扩散法
var longestPalindrome = function (s) {
if (s == null || s.length == 0) {
return "";
}
let strLen = s.length;
let left = 0;
let right = 0;
let len = 1;
let maxStart = 0;
let maxLen = 0;
for (let i = 0; i < strLen; i++) {
left = i - 1;
right = i + 1;
while (left >= 0 && s[left] == s[i]) {
len++;
left--;
}
while (right < strLen && s[right] == s[i]) {
len++;
right++;
}
while (left >= 0 && right < strLen && s[right] == s[left]) {
len = len + 2;
left--;
right++;
}
if (len > maxLen) {
maxLen = len;
maxStart = left;
}
len = 1;
}
return s.substring(maxStart + 1, maxStart + maxLen + 1);
};