Created
May 6, 2022 01:22
-
-
Save zakdances/68924dfe819b440bc9741c4ce370dd28 to your computer and use it in GitHub Desktop.
medium puzzle
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
// Given a string s, return the longest palindromic substring in s. | |
// Example 1: | |
// Input: s = "babad" | |
// Output: "bab" | |
// Explanation: "aba" is also a valid answer. | |
// Example 2: | |
// Input: s = "cbbd" | |
// Output: "bb" | |
// Constraints: | |
// 1 <= s.length <= 1000 | |
// s consist of only digits and English letters. | |
/** | |
* @param {string} s | |
* @return {string} | |
*/ | |
var longestPalindrome = function(s) { | |
if (s.length === 1) { | |
return s; | |
} | |
let longestPalindrome = ""; | |
// Find palendroms starting at center index | |
let centeredCreepOutwards = (string, start, end) => { | |
let atEdge = false; | |
while (atEdge === false && string[start] === string[end]) { | |
start -= 1; | |
end += 1; | |
atEdge = start >= 0 && end < string.length ? false : true; | |
} | |
return string.slice(start + 1, end); | |
} | |
for (let i = 0; i < s.length - 1; i++) { | |
let palindrome = centeredCreepOutwards(s, i, i); | |
let twoLetterPalindrome = centeredCreepOutwards(s, i, i + 1); | |
if (palindrome.length > longestPalindrome.length) { | |
longestPalindrome = palindrome; | |
} | |
if (twoLetterPalindrome.length > longestPalindrome.length) { | |
longestPalindrome = twoLetterPalindrome; | |
} | |
} | |
return longestPalindrome; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment