|
| 1 | +--- |
| 2 | +title: Leetcode 5. Longest Palindromic Substring |
| 3 | +description: Explanation for Leetcode 5 - Longest Palindromic Substring, and its solution in Python. |
| 4 | +date: 2025-05-06 |
| 5 | +categories: [Leetcode, Dynamic Programming, Medium] |
| 6 | +tags: [Leetcode, Python, Dynamic Programming, Medium] |
| 7 | +math: true |
| 8 | +--- |
| 9 | + |
| 10 | +## Problem |
| 11 | +[Leetcode 5 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/) |
| 12 | + |
| 13 | +Example: |
| 14 | +``` |
| 15 | +Input: s = "babad" |
| 16 | +Output: "bab" |
| 17 | +Explanation: "aba" is also a valid answer. |
| 18 | +
|
| 19 | +Input: s = "cbbd" |
| 20 | +Output: "bb" |
| 21 | +
|
| 22 | +Input: s = "a" |
| 23 | +Output: "a" |
| 24 | +
|
| 25 | +Input: s = "ac" |
| 26 | +Output: "a" |
| 27 | +``` |
| 28 | + |
| 29 | +## Approach |
| 30 | + |
| 31 | +We can solve this problem using Dynamic Programming. The idea is to maintain a 2D DP table where `dp[i][j]` is `True` if the substring `s[i:j+1]` is a palindrome. We iterate over all possible substrings and update the DP table accordingly. |
| 32 | + |
| 33 | +Here is the Python code for the solution: |
| 34 | +```python |
| 35 | +class Solution: |
| 36 | + def longestPalindrome(self, s: str) -> str: |
| 37 | + n = len(s) |
| 38 | + if n <= 1: |
| 39 | + return s |
| 40 | + |
| 41 | + dp = [[False] * n for _ in range(n)] |
| 42 | + start, max_length = 0, 1 |
| 43 | + |
| 44 | + # Every single character is a palindrome |
| 45 | + for i in range(n): |
| 46 | + dp[i][i] = True |
| 47 | + |
| 48 | + # Check for substrings of length 2 |
| 49 | + for i in range(n - 1): |
| 50 | + if s[i] == s[i + 1]: |
| 51 | + dp[i][i + 1] = True |
| 52 | + start = i |
| 53 | + max_length = 2 |
| 54 | + |
| 55 | + # Check for substrings of length 3 or more |
| 56 | + for length in range(3, n + 1): |
| 57 | + for i in range(n - length + 1): |
| 58 | + j = i + length - 1 |
| 59 | + if s[i] == s[j] and dp[i + 1][j - 1]: |
| 60 | + dp[i][j] = True |
| 61 | + start = i |
| 62 | + max_length = length |
| 63 | + |
| 64 | + return s[start:start + max_length] |
| 65 | +``` |
| 66 | + |
| 67 | +## Time Complexity and Space Complexity |
| 68 | + |
| 69 | +Time Complexity: $O(n^2)$ |
| 70 | +Space Complexity: $O(n^2)$ |
0 commit comments