Longest Palindromic Substring

problem [https://leetcode.com/problems/longest-palindromic-substring/ 5. Longest Palindromic Substring].

Problem description
Given a string, return the longest palindromic substring in.


 * Example 1
 * Input: s = "babad"
 * Output: "bab"
 * Note: "aba" is also a valid answer.


 * Example 2
 * Input: s = "cbbd"
 * Output: "bb"


 * Example 3
 * Input: s = "a"
 * Output: "a"


 * Example 4
 * Input: s = "ac"
 * Output: "a"


 * Constraints
 * consist of only digits and English letters (lower-case and/or upper-case).
 * consist of only digits and English letters (lower-case and/or upper-case).

Approach 1: Dynamic programming
We know that if a substring is already a palindrome, adding the same character on its both ends extends it into a longer palindrome. Hence we can use dynamic programming to solve the problem.

Let  be the length of the input. We can construct an  table of   rows and   columns, in which   will represent whether   is a palindromic substring.

We start from substring length 1, and increase substring length step-wise until we cover the entire input string.
 * Base case for substring length 1:.
 * Base case for substring length 2:.
 * For substring lengths greater than 2:.

Whenever we fill in the table, we keep track of the  we have found, and the   corresponding to the starting position of the substring with maximum length.

Once we fill up the table, we can obtain the result using  and.

Working example

 * Input: "google"
 * Final result:,  ,.

Complexity analysis
Let  be the length of the input string.


 * Space complexity
 * Since we created the  table with   rows and   columns, the space complexity is O( 2).


 * Time complexity
 * Since we created the  table with   rows and   columns, and each cell takes constant time to compute, the time complexity is O( 2).

Approach 2: Refined dynamic programming (O(1) space)
From the previous approach we can see that in order to extend a shorter palindrome into a longer palindrome, we only need to take care of the characters at both ends.

So we can employ another strategy: start from the middle, and expand in both directions.
 * The middle contains either 1 or 2 characters. Set two pointers  and   to start from the middle.
 * Move  towards the left, and   towards the right.
 * Stop expanding when we encounter two different characters on both ends, because from that point on constructing a palindrome is no longer possible.

Complexity analysis

 * Space complexity
 * Since we have used the  and   pointers instead of creating the   table, we can achieve O(1) space complexity.


 * Time complexity
 * Let  be the input string's length. We have   letters to start with, and each letter is expanded at most   times (for constructing odd-length and even-length palindromes). So the total time complexity is O( 2).