Problem Statement
Given a string S, find the longest palindromic substring of S.
def longest_palindromic_substring(s):
if not s:
return None
n = len(s)
lps, lps_len = s[0], 1
dp = [[0 for i in xrange(n)] for j in xrange(n)]
for i in xrange(n):
dp[i][i] = 1
for i in xrange(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = 2
if dp[i][i + 1] > lps_len:
lps = s[i : i + 2]
lps_len = dp[i][i + 1]
for length in xrange(3, n + 1):
for start in xrange(n - length + 1):
end = start + length - 1
if s[start] == s[end] and dp[start + 1][end - 1]:
lps = s[start : start + length]
lps_len = length
dp[start][end] = length
return lps
Analysis: O(n2) time complexity, O(n2) space complexity.