Created
February 28, 2019 05:42
-
-
Save userkang/160769be8f0178f100c181b5581c548b to your computer and use it in GitHub Desktop.
最大回文子串
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {string} | |
*/ | |
var longestPalindrome = function(s) { | |
if (!s) return ''; | |
var longest = s[0]; | |
var expandAroundCenter = function (left, right) { | |
while (left >= 0 && right < s.length && s[left] === s[right]) { | |
left--; | |
right++; | |
} | |
return s.slice(left + 1, right); | |
} | |
for (var i = 0; i < s.length; i++) { | |
// 奇数 | |
var odd = expandAroundCenter(i, i); | |
if (odd.length > longest.length) longest = odd; | |
// 偶数 | |
var even = expandAroundCenter(i, i + 1); | |
if (longest.length < even.length) longest = even; | |
} | |
return longest; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment