LC005 - Longest Palindromic Substring
Problem
Given a string s
, return the longest palindromic substring in s
Example
Input: s = “babad”
Output: “bab”
Explanation: “aba” is also a valid answer
Solution
Naive
In the naive solution, we check every substring to see if it is a palindrome and take the longest one. This approach is in time complexity.
Improved
Intuitively, we can check whether or not a substring is a palindrome from its center, which is cheaper than checking it from its edges. We can iterate across the characters in the string array and expand outwards from each character to check whether or not it is a palindrome, and if so, how long it is. Time complexity of this approach will be , and we don't use extra space so space complexity is .
Optimal
We can use Manacher’s algorithm to solve problems involving palindromes in time. However, this is usually beyond the scope of a normal interview.
Last updated