|
| 1 | +--- |
| 2 | +id: Longest Palindromic Substring |
| 3 | +title: Longest Palindromic Substring(LeetCode) |
| 4 | +sidebar_label: 0005-Longest Palindrome Substring |
| 5 | +tags: |
| 6 | + - String |
| 7 | + - Dynamic Programming |
| 8 | +description: Given a string s, return the longest palindromic substring in s. |
| 9 | +--- |
| 10 | + |
| 11 | +## Problem Description |
| 12 | + |
| 13 | +| Problem Statement | Solution Link | LeetCode Profile | |
| 14 | +| :-------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | |
| 15 | +| [Longest Palindromic Substring on LeetCode](https://leetcode.com/problems/longest-palindromic-substring/description/) | [Longest Palindromic Substring Solution on LeetCode](https://leetcode.com/problems/longest-palindromic-substring/editorial/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | |
| 16 | + |
| 17 | +## Problem Statement |
| 18 | + |
| 19 | +Given a string `s`, return the longest palindromic substring in `s`. |
| 20 | + |
| 21 | +### Examples |
| 22 | + |
| 23 | +**Example 1:** |
| 24 | +```plaintext |
| 25 | +Input: s = "babad" |
| 26 | +Output: "bab" |
| 27 | +Explanation: "aba" is also a valid answer. |
| 28 | +``` |
| 29 | + |
| 30 | +**Example 2:** |
| 31 | +```plaintext |
| 32 | +Input: s = "cbbd" |
| 33 | +Output: "bb" |
| 34 | +``` |
| 35 | + |
| 36 | +### Constraints |
| 37 | +- `1 <= s.length <= 1000` |
| 38 | +- `s` consist of only digits and English letters. |
| 39 | + |
| 40 | +## Solution |
| 41 | + |
| 42 | +### Approach 1: Check All Substrings |
| 43 | + |
| 44 | +#### Intuition |
| 45 | +We can start with a brute-force approach. We will simply check if each substring is a palindrome, and take the longest one that is. |
| 46 | + |
| 47 | +#### Algorithm |
| 48 | +1. Create a helper method `check(i, j)` to determine if a substring is a palindrome. |
| 49 | +2. Use two pointers to iterate from the start and end of the substring towards the center. |
| 50 | +3. If characters at both pointers are equal, move the pointers inward. |
| 51 | +4. Use nested loops to check all possible substrings and use the helper method to determine if they are palindromes. |
| 52 | +5. Keep track of the longest palindrome found. |
| 53 | + |
| 54 | +#### Implementation |
| 55 | +```python |
| 56 | +def longestPalindrome(s: str) -> str: |
| 57 | + def check(l, r): |
| 58 | + while l >= 0 and r < len(s) and s[l] == s[r]: |
| 59 | + l -= 1 |
| 60 | + r += 1 |
| 61 | + return s[l+1:r] |
| 62 | + |
| 63 | + longest = "" |
| 64 | + for i in range(len(s)): |
| 65 | + odd_palindrome = check(i, i) |
| 66 | + even_palindrome = check(i, i + 1) |
| 67 | + longest = max(longest, odd_palindrome, even_palindrome, key=len) |
| 68 | + |
| 69 | + return longest |
| 70 | +``` |
| 71 | + |
| 72 | +### Complexity Analysis |
| 73 | +- **Time complexity**: $O(n^3)$ - We check each substring, and checking each substring takes $O(n)$ time. |
| 74 | +- **Space complexity**: $O(1)$ - We use a constant amount of extra space. |
| 75 | + |
| 76 | +### Approach 2: Dynamic Programming |
| 77 | + |
| 78 | +#### Intuition |
| 79 | +If we know a substring is a palindrome, we can extend it if the characters on both ends match. |
| 80 | + |
| 81 | +#### Algorithm |
| 82 | +1. Initialize a 2D DP table with `False`. |
| 83 | +2. Mark all single-character substrings as palindromes. |
| 84 | +3. Check substrings of length 2 and mark them if characters match. |
| 85 | +4. Use the table to extend palindromes to longer substrings. |
| 86 | +5. Keep track of the longest palindrome found. |
| 87 | + |
| 88 | +#### Implementation |
| 89 | +```python |
| 90 | +def longestPalindrome(s: str) -> str: |
| 91 | + n = len(s) |
| 92 | + dp = [[False] * n for _ in range(n)] |
| 93 | + longest = "" |
| 94 | + |
| 95 | + for i in range(n): |
| 96 | + dp[i][i] = True |
| 97 | + longest = s[i] |
| 98 | + |
| 99 | + for i in range(n-1): |
| 100 | + if s[i] == s[i+1]: |
| 101 | + dp[i][i+1] = True |
| 102 | + longest = s[i:i+2] |
| 103 | + |
| 104 | + for length in range(3, n+1): |
| 105 | + for i in range(n-length+1): |
| 106 | + j = i + length - 1 |
| 107 | + if s[i] == s[j] and dp[i+1][j-1]: |
| 108 | + dp[i][j] = True |
| 109 | + longest = s[i:j+1] |
| 110 | + |
| 111 | + return longest |
| 112 | +``` |
| 113 | + |
| 114 | +### Complexity Analysis |
| 115 | +- **Time complexity**: $O(n^2)$ - We fill an `n * n` table. |
| 116 | +- **Space complexity**: $O(n^2)$ - We use an `n * n` table to store the DP results. |
| 117 | + |
| 118 | +### Approach 3: Expand From Centers |
| 119 | + |
| 120 | +#### Intuition |
| 121 | +A palindrome mirrors around its center. We can expand around potential centers to find palindromes. |
| 122 | + |
| 123 | +#### Algorithm |
| 124 | +1. Consider each character and pair of characters as potential centers. |
| 125 | +2. Expand around each center to find the longest palindrome. |
| 126 | +3. Keep track of the longest palindrome found. |
| 127 | + |
| 128 | +#### Implementation |
| 129 | +```python |
| 130 | +def longestPalindrome(s: str) -> str: |
| 131 | + def expandAroundCenter(s, left, right): |
| 132 | + while left >= 0 and right < len(s) and s[left] == s[right]: |
| 133 | + left -= 1 |
| 134 | + right += 1 |
| 135 | + return s[left + 1:right] |
| 136 | + |
| 137 | + if not s: |
| 138 | + return "" |
| 139 | + |
| 140 | + longest = s[0] |
| 141 | + |
| 142 | + for i in range(len(s)): |
| 143 | + odd_palindrome = expandAroundCenter(s, i, i) |
| 144 | + even_palindrome = expandAroundCenter(s, i, i + 1) |
| 145 | + longest = max(longest, odd_palindrome, even_palindrome, key=len) |
| 146 | + |
| 147 | + return longest |
| 148 | +``` |
| 149 | + |
| 150 | +### Complexity Analysis |
| 151 | +- **Time complexity**: $O(n^2)$ - We expand around each center, which takes $O(n)$ time. |
| 152 | +- **Space complexity**: $O(1)$ - We use a constant amount of extra space. |
| 153 | + |
| 154 | +### Approach 4: Manacher's Algorithm |
| 155 | + |
| 156 | +#### Intuition |
| 157 | +Manacher's algorithm can find the longest palindromic substring in linear time. |
| 158 | + |
| 159 | +#### Algorithm |
| 160 | +1. Transform the string to handle even-length palindromes. |
| 161 | +2. Use a helper array to store the length of the palindrome at each position. |
| 162 | +3. Use the properties of palindromes and the helper array to efficiently find the longest palindrome. |
| 163 | + |
| 164 | +#### Implementation |
| 165 | +```python |
| 166 | +def longestPalindrome(s: str) -> str: |
| 167 | + if not s: |
| 168 | + return "" |
| 169 | + |
| 170 | + # Transform s into new string with inserted boundaries |
| 171 | + T = '#'.join(f"^{s}$") |
| 172 | + n = len(T) |
| 173 | + P = [0] * n |
| 174 | + C = R = 0 |
| 175 | + |
| 176 | + for i in range(1, n - 1): |
| 177 | + P[i] = (R > i) and min(R - i, P[2 * C - i]) |
| 178 | + while T[i + P[i] + 1] == T[i - P[i] - 1]: |
| 179 | + P[i] += 1 |
| 180 | + if i + P[i] > R: |
| 181 | + C, R = i, i + P[i] |
| 182 | + |
| 183 | + max_len, center_index = max((n, i) for i, n in enumerate(P)) |
| 184 | + return s[(center_index - max_len) // 2: (center_index + max_len) // 2] |
| 185 | +``` |
| 186 | + |
| 187 | +### Complexity Analysis |
| 188 | +- **Time complexity**: $O(n)$ - Manacher's algorithm runs in linear time. |
| 189 | +- **Space complexity**: $O(n)$ - We use an array of length `n` to store the lengths of palindromes. |
| 190 | + |
| 191 | +### Conclusion |
| 192 | +We discussed four approaches to solve the "Longest Palindromic Substring" problem, each with varying complexities and trade-offs. The dynamic programming and center expansion approaches provide a good balance of simplicity and efficiency for practical use cases, while Manacher's algorithm offers the optimal theoretical performance. |
| 193 | +``` |
| 194 | +
|
0 commit comments