Problem Description:
Given a string S, find the longest palindromic substring ins. The maximum length of S is assume, and there exists one unique longest palindromic substring.
Basic idea:
The Navie solution of the subject is to test if each (I,J) i<=j is a palindrome, and record the maximum condition. O (n^3)
If you look both ways from the center of a palindrome, you only need the complexity of O (n^2). This method is to determine each point as a palindrome string, and record and maintain the longest back text string. For ease of handling, you can insert a special character "#" in each of the two characters in a string, so that the processing of even palindrome strings and odd palindrome strings can be Fu Yi together.
Code:
Public String Longestpalindrome (string s) { //java if (s.length () <= 1) return s; String tmpstr = "#"; for (int i = 0; I <s.length (); i++) tmpstr + = S.charat (i) + "#"; String max = ""; for (int i = 1; i<tmpstr.length ()-1; i=i+1) { int toleft = i-1; int toright = i+1; while (ToLeft >=0 && toright <tmpstr.length ()) { if (tmpstr.charat)! = ToLeft (Tmpstr.charat) ) Break ; else { toleft--; toright++; } } if (Toright-toleft-2 > Max.length ()) max = tmpstr.substring (toleft+1,toright); } Return Max.replaceall ("#", ""); }
[Leetcode] Longest palindromic Substring