Problem Description:
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.
Problem Solving Ideas:
Traversal method with a time complexity of O (n). It starts from the beginning of the string, and then spreads from the position to the sides in each traversal until the longest sub-palindrome is found. You also need to consider the case of odd and even strings.
The code is as follows:
1 Public classSolution {2 Publicstring Longestpalindrome (string s) {3 intn =s.length ();4String longest = s.substring (0, 1);5 6 if(s = =NULL|| S.length () = = 0)7 return NULL;8 for(inti = 0; I < n; i++) {9String P1 =Expandfromcenter (S, I, I);Ten if(P1.length () >longest.length ()) OneLongest =P1; AString P2 = expandfromcenter (s, I, i + 1); - if(P2.length () >longest.length ()) -Longest =P2; the } - returnlongest; - } - + PublicString Expandfromcenter (String s,intC1,intC2) { - intHead =C1; + intTail =C2; A intm =s.length (); at - while(Head >= 0 && tail < m && S.charat (head) = =S.charat (tail)) { -head--; -tail++; - } - returnS.substring (head + 1), tail); in } -}
Java [Leetcode 5] Longest palindromic Substring