Created
February 1, 2023 12:49
-
-
Save pitsanujiw/4da3ad32522dfc1f4ce5aef5c5705458 to your computer and use it in GitHub Desktop.
This file contains 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} str | |
* @returns {string} | |
*/ | |
function longestPalindrome(str) { | |
if (!str?.length) { | |
return ""; | |
} | |
let results = str[0]; | |
for (let i = 1; i < str.length; i++) { | |
let char = str[i]; | |
let left = i; | |
let right = i; | |
while (left > 0 && str[left - 1] === char) { | |
left--; | |
} | |
while (right < str.length && str[right + 1] === char) { | |
right++; | |
i++; | |
} | |
console.log("start left", left); | |
while ( | |
left >= 0 && | |
right < str.length - 1 && | |
str[left - 1] === str[right + 1] | |
) { | |
left--; | |
right++; | |
} | |
if (results.length < right - left + 1) { | |
results = str.slice(left, right + 1); | |
} | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment