Longest Palindromic Substring
Medium
Dynamic ProgrammingString
Problem
Return the longest palindromic substring of s.
Example 1
Input: "babad"
Output: "bab" or "aba"
Example 2
Input: "cbbd"
Output: "bb"
Constraints
- 1 ≤ s.length ≤ 1000
Approach — Dynamic Programming
This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) to O(n²) time.
Solution code
Python
class Solution:
def longestPalindrome(self, s):
if not s:
return ''
start, end = 0, 0
def expand(l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1; r += 1
return l + 1, r - 1
for i in range(len(s)):
for l, r in (expand(i, i), expand(i, i+1)):
if r - l > end - start:
start, end = l, r
return s[start:end+1]
Java
class Solution {
public String longestPalindrome(String s) {
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int a = expand(s, i, i), b = expand(s, i, i + 1);
int len = Math.max(a, b);
if (len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; }
}
return s.substring(start, end + 1);
}
private int expand(String s, int l, int r) {
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; }
return r - l - 1;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Longest Palindromic Substring interactively → ← All solutions