A linear solution can be found along this path:
Prequisities:
(one). You need to know how to build a suffix array in O (N) or O (NlogN) time.
(2). You need to know how to find the standard LCP array, i.e. LCP between adjacent suffixes i and i-1
those. LCP [i] = LCP (suffix i in a sorted array, suffix i-1 in a sorted array) for (i> 0).
Let S be the original string, and S 'the reverse side of the original string. Let's take S = " banana " as an example. Then its return line is S '= ananab.
Step 1 : combine S + # + S ' to get String Str, where # is the alphabet that is not in the original string.
Concatenated String Str=S+
Step 2: Now build an array of str suffix.
In this example, the suffix array is:
Suffix Number Index Sorted Suffix 0 6 #ananab 1 5 a#ananab 2 11 ab 3 3 ana#ananab 4 9 anab 5 1 anana#ananab 6 7 ananab 7 12 b 8 0 banana#ananab 9 4 na#ananab 10 10 nab 11 2 nana#ananab 12 8 nanab
Note that the suffix array is an array of integers giving the starting positions of the suffixes of the string in lexicographic order. So, the array containing the index of the starting position is an array of suffixes.
This is SuffixArray [] = {6,5,11,3,9,1,7,12,0,4,10,2,8};
Step 3 Since you were able to create an array of suffix, find the longest common prefixes between adjacent suffixes .
LCP between
Thus, the LCP array is LCP = {0,0,1,1,3,3,5,0,1,0,2,2,4}.
Where LCP [i] = The length of the longest common prefix between the suffix i and the suffix (i-1). (for i> 0)
Step 4:
Now you have built the LCP array, use the following logic.
Let the length of the Longest Palindrome ,longestlength:=0 (Initially) Let Position:=0. for(int i=1;i<Len;++i) { //Note that Len=Length of Original String +"#"+ Reverse String if((LCP[i]>longestlength)) { //Note Actual Len=Length of original Input string . if((suffixArray[i-1]<actuallen && suffixArray[i]>actuallen)||(suffixArray[i]<actuallen && suffixArray[i-1]>actuallen)) { //print :Calculating Longest Prefixes b/w suffixArray[i-1] AND suffixArray[i] longestlength=LCP[i]; //print The Longest Prefix b/w them is .. //print The Length is :longestlength:=LCP[i]; Position=suffixArray[i]; } } } So the length of Longest Palindrome :=longestlength; and the longest palindrome is:=Str[position,position+longestlength-1];
Execution Example ::
actuallen=Length of banana:=6 Len=Length of "banana#ananab" :=13. Calculating Longest Prefixes b/wa
Just take a note ::
The if condition in step 4 basically refers to the fact that at each iteration (i), if I accept the suffixes s1 (i) and s2 (i-1), then "s1 should contain # and s2 should not contain #" OR " s2 must contain # and s1 must not contain # ".
|(1:BANANA#ANANAB)|leaf tree:| | | | |(7:#ANANAB)|leaf | | |(5:NA)| | | | |(13:B)|leaf | |(3:NA)| | | |(7:#ANANAB)|leaf | | | | | |(13:B)|leaf |(2:A)| | |(7:#ANANAB)|leaf | | | |(13:B)|leaf | | | |(7:#ANANAB)|leaf | |(5:NA)| | | |(13:B)|leaf |(3:NA)| | |(7:#ANANAB)|leaf | | | |(13:B)|leaf | |(7:#ANANAB)|leaf