Given a string, find the longest substring that is also a palondrom.
One simple solution is to find reverse of S and then find the longest common substring between S and reverse(s). This is also be the longest palindromic substring. That is,
LongestPalindromicSubStr(S) = LCS(S, reverse(S)).
LCS can be solved by DP in O(n^2) time and O(n^2) space. Look into my previous post on LCS for details implementation of LCS problem using DP.
We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2N-1 such centers.
You might be asking why there are 2N-1 but not N centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") and its center are between the two 'b's.
Since expanding a palindrome around its center could take O(N) time, the overall complexity is O(N2).
Read full article from Longest palindromic substring in O(n^2) time - Algorithms and Problem SolvingAlgorithms and Problem Solving
No comments:
Post a Comment