Algorithm Day94 - Longest Palindromic Substring
π§© Problem Description
Given a string s, return the longest palindromic substring in s.
A palindrome is a string that reads the same backward as forward.
π¬ Examples
Example 1
1 | Input: s = "babad" |
Example 2
1 | Input: s = "cbbd" |
π‘ Intuition
We can solve this using Dynamic Programming or Expand Around Center.
πΉ Approach 1 β Expand Around Center
Every palindrome mirrors around its center.
There can be 2n - 1 centers (between characters and at characters).
Expand from each center until itβs no longer a palindrome.
π’ Java Code (Expand Around Center)
1 | class Solution { |
πΉ Approach 2 β Dynamic Programming
Let dp[i][j] mean whether substring s[i..j] is a palindrome.
Transition rule:
1 | dp[i][j] = (s[i] == s[j]) && (j - i < 3 || dp[i + 1][j - 1]) |
π’ Java Code (Dynamic Programming)
1 | class Solution { |
β± Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Expand Around Center | O(nΒ²) | O(1) |
| Dynamic Programming | O(nΒ²) | O(nΒ²) |
βοΈ Summary
- Expand around every center or use DP.
- Palindrome means symmetry around a center.
- Expand method is simpler and more space-efficient.
Related problems:
lc-516(Longest Palindromic Subsequence)lc-647(Palindromic Substrings)