Longest Palindromic Substring

Medium

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Examples:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Input: "cbbd"
Output: "bb"

Solution

var longestPalindrome2 = function(s) {
  if (!s) return ''
  let longest = s[0]
  let expandAroundCenter = function (left, right) {
    while (left >= 0 && right < s.length && s[left] === s[right]) {
      left--
      right++
    }
    return s.slice(left + 1, right)
  }
  for (let i = 0; i < s.length; i++) {
    // 奇数
    let odd = expandAroundCenter(i, i)
    if (odd.length > longest.length) longest = odd
    // 偶数
    let even = expandAroundCenter(i, i + 1)
    if (longest.length < even.length) longest = even
  }
  return longest
}