5. longest Palindromic Substring

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"

Thoughs:

  1. O(n^2) with DP or center expansion, O(n) with Manacher’s algorithm

  2. the number between left and right (exclusive) is "right - left - 1" and number from left and right (inclusive) is "right - left + 1"

Code (O (n^2) DP)

Code (O (n^2) without extra space)

Code (O(n)) with Manacher's algorithm

Last updated

Was this helpful?