Wow, this one is a beast – also took me an entire afternoon.
The problem is: given a string, find the longest palindromic substring.
The first approach I thought of was brute force – just get it working first.
How to brute force? My initial idea was:
Use a fixed function check to determine if a string is a palindrome.
If s is a palindrome, we’re done.
Otherwise, check s(0, s.length()-2) and s(1, s.length()-1).
I wrote this code and tested it – works fine for short strings. But thinking about it, the complexity is way too high, especially for slightly longer strings.
Sure enough, it timed out.
TLE means the approach is wrong – time to rethink.
Let’s try the reverse approach:
First check if s[i] is a palindrome, then expand by 1 on each side.
Then check if s[i], s[i+1] is a palindrome, then expand by 1 on each side.
The two cases are needed because of the odd/even length distinction.
OK, this should optimize the time for most cases.
But still TLE. However, we’re getting closer to the solution.
Here’s the next insight: we don’t actually need to expand by 1 each time. If we’ve already found a palindrome of length sum, when we enumerate the next center point, we can start expanding from sum/2. And that got AC!
The few WAs were just boundary issues.
| |