Longest palindromic Substring

Source: Internet
Author: User

1. Question

Find the longest palindrome string

Given A string S, find the longest palindromic substring in S. The maximum length of S is assume, and there exists one unique longest palindromic substring.
2. Solution2.1 O (N3)

For each character, examine whether the substring (as the first character) and its remaining characters (as the trailing character) are palindrome strings, finding the longest. Determine if a palindrome is time-consuming O (n), so the Complexity O (N3)

2.2 O (N2) 2.2.1 Center Outward expansion method

For each character, it is used as the center character of the palindrome string (by inserting auxiliary characters so that only the odd palindrome case is considered, eg. ABCD---> #a #b#c#d#), considering the length of its longest palindrome string. In this case, O (n) is retrieved for each central character, so time complexity O (n2)

1  Public classSolution {2     Private intMaxstart;3     Private intMaxend;4     5     Private voidExpand (String S,intFromintend) {6          for(; from>=0 && end<s.length () && (S.charat (from) = = S.charat (end)); from--, end++ );7end--;8from++;9         if(End-from > maxend-Maxstart) {TenMaxstart =from ; OneMaxend =end; A         } -     } -      the     //expand from a middle point, O (n2) time -      Publicstring Longestpalindrome (string s) { -Maxstart = 0; -Maxend = 0; +          for(inti=0; I<s.length ()-1; i++ ){ -expand (S,i,i);//The result length is odd +expand (s,i,i+1);//The result length is even A         } at         returnS.substring (Maxstart, maxend+1); -     } -}
Expandfrommiddle

2.2.2 is expanded by length

In retrieving the text string, the general is to see the shorter palindrome string, and then slowly outward expansion (similar to the center outward expansion), that is, first find the length of 2 palindrome string, and then find the length of 3, for 4 ... Long lengths of information can be reused for short lengths.

Thus, the definition of a two-dimensional array a[][] stores palindrome information, A[i][j] Indicates whether the character I to J is a palindrome string, there are:

A[i][i] = true;

A[i][i+1] = (chars[i] = = chars[i+1]);

A[I][J] = (chars[i] = = Chars[j]) && a[i+1][j-1];

1  Public classSolution {2     //DP, O (n2) time3      Publicstring Longestpalindrome (string s) {4         if(S.length () ==1)returns;5         if(s.length () = = 2 ){6             if(S.charat (0) = = S.charat (1) )7                 returns;8             returnS.substring (0, 1);9         }Ten         //s.length () >2 One         Boolean[] p =New Boolean[S.length ()][s.length ()]; A         inti; -          for(i=0; I<s.length ()-1; i++ ){ -P[i][i] =true; theP[i][i+1] = (S.charat (i) = = S.charat (i+1) ); -         } -P[i][i] =true;  -          for(i=2; I<s.length (); i++ ) +              for(intJ=0, k=i; K<s.length (); J + +, k++ ) -P[j][k] = (S.charat (j) = = S.charat (k)) && p[j+1][k-1]; +          A         intMaxstart = 0; at         intMaxend = 0; -          for(i=0; I<s.length (); i++ ) -              for(intJ=s.length ()-1; j>=i; j-- ){ -                 if(P[i][j]) { -                     if(J-i > maxend-Maxstart) { -Maxstart =i; inMaxend =J; -                     } to                      Break; +                 } -             } the         returnS.substring (Maxstart, maxend+1); *     } $}
Expandlength2.3 O (N)

Considering the center outward expansion, it iterates through each character for its retrieve string. In fact, because of the symmetry of palindrome string, the center of the left side of the palindrome and the right side of the character of the partial palindrome is consistent, this part of the data can be reused, rather than repeating the calculation.

Refine the algorithm above and redefine the following variables:

    • R[]: Stores the radius of the longest palindrome with the center point of each point (to reuse this information)
    • Max: Store The current palindrome to the Farthest center character index, that is, a palindrome string centered on Max, and the last character of the palindrome string is the furthest one. Hereinafter referred to as Max as the farthest coverage point, the Palindrome range is the coverage range
    • I: Define the character index of the current access, to calculate the length of the palindrome string for the character I
      • If I is in Max's coverage, examine the coverage of the symmetry point of I
        • If the symmetric point overlay boundary is within the max overlay boundary, then I need not extend to I, r[i] = R[i symmetry Point]
        • If the symmetric point overlay boundary is coincident with the max overlay boundary, then for I, the point beyond the farthest cover boundary is the next possible character in the palindrome range of I, and should continue to expand outward from the farthest covering boundary, to calculate r[i]
      • If not, expand outward with I as the center point (there is no information available at this time)

Using the asymptotic calculation analysis, it is known that the algorithm has a time complexity of O (n)

1  Public classSolution {2     3     //adding extra character to make all substring as an odd number string. Such AS:ABCD---> #a #b#c#d#4     Privatestring Preprocess (string s) {5StringBuilder res =NewStringBuilder ();6          for(inti=0; I<s.length (); i++ ){7Res.append (' # '));8 Res.append (S.charat (i));9         }TenRes.append (' # ') ); One         returnres.tostring (); A     } -      -     //expand a palindrome, return the expanding length the     Private intExpand (String S,intStartintend) { -         intNewS =start; -         intNewe =end; -          for(; news >= 0 && Newe < s.length () && S.charat (news) = = S.charat (newe); News--, newe++ ); +         returnStart-NewS; -     } +      A     //O (n) time, using symmetry feature, calculate the longest palindromic centered by at      Publicstring Longestpalindrome (string s) { -String NewS =preprocess (s); -          -         int[] r =New int[News.length ()]; -R[0] = 0; -         intMax = 0; in          -          for(intI=1; I<news.length (); i++ ){ to             intj = R[max] + max;//present farthest palindrome range, inclusive +             if(J >=news.length ()) -                  Break; the             //If I is in the range, it's possible to fast calculate the palindromic length for point I *             if(i<=j) { $                 intSymi = r[2*max-i];Panax Notoginseng                 intRemainrange = J-i; -                 if(Symi <Remainrange) theR[i] =Symi; +                 Else AR[i] = expand (NewS, I-remainrange-1, j+1) +Remainrange; the             } +             //if I is not int the range, r[i] = expand (i) -             Else $R[i] = expand (NewS, I-1, i+1 ); $              -             if(R[i] + i > J) max =i; -         } theMax = 0; -          for(inti=0; i<r.length; i++ )Wuyi             if(R[i] > R[max]) max =i; the         returnS.substring ((max-r[max]+1)/2, (Max+r[max])/2 ); -     } Wu}
Betterexpandfrommiddle

    

Longest palindromic Substring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.