Problem 57
Longest Palindromic Substring
Medium · 20 pts · String, Dynamic Programming, Two Pointers
Problem
You are given a string S. Print its longest palindromic substring: the longest contiguous block of S that reads the same forwards and backwards. If several palindromic substrings share the maximum length, print the one that starts first (leftmost). Every palindrome has a centre, either a single character (odd length) or the gap between two characters (even length). Expanding outwards from each of the 2N - 1 possible centres while the characters on both sides match gives an O(N²) solution.
Input
A single string S of lowercase English letters.
Output
Print the longest palindromic substring.
Constraints
1 <= |S| <= 1000
Example input
babad
Example output
bab
Explanation
In "babad", both "bab" (starting at index 0) and "aba" (starting at index 1) are palindromes of length 3, and no palindrome of length 4 or 5 exists. "bab" starts first, so it is the answer.