题目
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
Example 1:
1 2 3 4 5 6 7 Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
解题思路
从左向右依次遍历字符串.
以当前字符(假设回文数为基数长度)或当前字符和下一个字符(假设回文数为偶数长度)为回文数中心, 向左右两侧搜索.
时间复杂度 O ( n 2 ) O(n^2) O ( n 2 )
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 const longestPalindrome = function (s ) { const len = s.length ; if (len <= 1 ) { return s; } let maxPalStrLeft = 0 , maxPalStrRight = 0 ; const expandAroundCenter = (left, right ) => { while (left >= 0 && right < len && s[left] === s[right]) { left--; right++; } left++; right--; if (right - left > maxPalStrRight - maxPalStrLeft) { maxPalStrLeft = left; maxPalStrRight = right; } }; for (let i = 0 ; i < len; i++) { expandAroundCenter (i, i); expandAroundCenter (i, i + 1 ); } return s.slice (maxPalStrLeft, maxPalStrRight + 1 ); }; console .log (longestPalindrome ('babad' ));console .log (longestPalindrome ('cbbd' ));console .log (longestPalindrome ('bacd' ));console .log (longestPalindrome ('a' ));console .log (longestPalindrome ('bananas' ));console .log (longestPalindrome ('aaabaaaa' ));console .log (longestPalindrome ('ab' ));
边界情况:
以字符串 ab 为例, 调用 expandAroundCenter(i, i + 1), 即expandAroundCenter(1, 2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 const expandAroundCenter = (left, right ) => { while (left >= 0 && right < len && s[left] === s[right]) { left--; right++; } left++; right--; if (right - left > maxPalStrRight - maxPalStrLeft) { maxPalStrLeft = left; maxPalStrRight = right; } }; expandAroundCenter (1 , 2 )