Overview
Given a string s, return the longest palindromic substring in s.
If there are multiple answers of the same length, return the first one found.
Constraints
1 <= s.length <= 1000sconsists of only lowercase English letters.- O(n²) expand-around-center is the expected approach.
Examples
longestPalindrome("babad");
// => "bab" (or "aba" — both valid)longestPalindrome("cbbd");
// => "bb"
longestPalindrome("a");
// => "a"Solution
Reveal solution
function longestPalindrome(s) {
let start = 0, maxLen = 1;
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) {
if (r - l + 1 > maxLen) {
start = l;
maxLen = r - l + 1;
}
l--;
r++;
}
}
for (let i = 0; i < s.length; i++) {
expand(i, i); // odd-length
expand(i, i + 1); // even-length
}
return s.substring(start, start + maxLen);
}Expand around every index as center for both odd and even length palindromes. O(n²) time, O(1) space.
Resources
longest-palindromic-substring.js
Find the Longest Palindromic Substring
mediumcodingAlgorithmsStrings
Overview
Given a string s, return the longest palindromic substring in s.
If there are multiple answers of the same length, return the first one found.
Constraints
1 <= s.length <= 1000sconsists of only lowercase English letters.- O(n²) expand-around-center is the expected approach.
Examples
longestPalindrome("babad");
// => "bab" (or "aba" — both valid)longestPalindrome("cbbd");
// => "bb"
longestPalindrome("a");
// => "a"Solution
Reveal solution
function longestPalindrome(s) {
let start = 0, maxLen = 1;
function expand(l, r) {
while (l >= 0 && r < s.length && s[l] === s[r]) {
if (r - l + 1 > maxLen) {
start = l;
maxLen = r - l + 1;
}
l--;
r++;
}
}
for (let i = 0; i < s.length; i++) {
expand(i, i); // odd-length
expand(i, i + 1); // even-length
}
return s.substring(start, start + maxLen);
}Expand around every index as center for both odd and even length palindromes. O(n²) time, O(1) space.
Resources
NameTopicDifficulty
103 of 103 problems