5 Longest Palindromic Substring

1. Question

Given a strings, find the longest palindromic substring ins. You may assume that the maximum length ofsis 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

2. Implementation

(1) DP

思路: 我们用一个2维 boolean数组dp[i][j]判断substring s[i...j]是否为Palindrome, 如果dp[i][j]是true的话,比较当前得到的是palindrome的substring和res的长度大小,比res长度大的话则更新res

3. Time & Space Complexity

DP: 时间复杂度O(n^2), 空间复杂度O(n^2)

Last updated

Was this helpful?