24. Longest Palindromic Substring

Medium · String

Given a string, find the longest contiguous substring that reads the same forwards and backwards (a palindrome). If multiple palindromes have the same maximum length, return the one that appears first in the string.

A palindrome is a sequence of characters that is identical when reversed. Single characters are considered palindromes.

Examples

Example 1
Input: "babad"
Output: "bab"
Explanation: Both "bab" and "aba" are valid palindromes of length 3. "bab" appears first (starting at index 0), so it is returned.
Example 2
Input: "cbbd"
Output: "bb"
Explanation: The longest palindromic substring is "bb" with length 2.

Constraints