https://leetcode.com/problems/longest-palindromic-substring/
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.Given the string =
"abcdzdcab", return"cdzdc".Solution Reference: http://articles.leetcode.com/longest-palindromic-substring-part-i
Solution 1: Brute Force
1 | // Time Complexity O(N^3) |
Solution 2: Dynamic Programming
1 | Define P[ i, j ] ← true iff the substring Si … Sj is a palindrome, otherwise false. |
Therefore,
1 | P[ i, j ] ← ( P[ i+1, j-1 ] and Si = Sj ) |
The base cases are:
1 | P[ i, i ] ← true |
1 | // Time Complexity O(N^2), Space Complexity O(N^2) |
Solution 3
1 | // Time Complexity: O(N^2), Space Complexity O(1) |