The largest palindrome in a string (question 5th)
Given A string s, find the longest palindromic substring in S. Assume that the maximum length of SIS 1000.
Example:
Input: "Babad" Output: "Bab" note: "ABA" is also a valid answer.
Example:
Input: "CBBD" Output: "BB"
1. My solution (accepted): Center expansion
Idea: Palindrome means that there is a center, a traversal, for each position on the number of the largest palindrome can be, the initial processing pruning, merging the same elements, such as xxxxaaaxxxx, the first constant level of a merge out; Traverse time to prune again, traversed by a maxlen, if the element is about to traverse the maximum possible palindrome length can not exceed maxlen, no longer traverse.
1 Public Static voidMain (string[] args) {2String str = "Ababababa";3 System.out.println (Longestpalindrome (str));4 5 }6 7 Public Staticstring Longestpalindrome (string s) {8 if(s = =NULL) {9 return NULL;Ten } One Char[] chars =S.tochararray (); A intLength =chars.length; - intMaxLen = 0; -String maxstr = ""; the - for(inti = 0; i < length; i++) { - - //Cut Branch + intPossiblelength =getmaxpossiblelength (i, length); - if(Possiblelength <maxlen) { + Continue; A } at -String maxstrtmp =Getmaxstrbyindex (i, chars); - if(MaxLen <maxstrtmp.length ()) { -MaxLen =maxstrtmp.length (); -Maxstr =maxstrtmp; - } in } - returnMaxstr; to } + - Private Static intGetmaxpossiblelength (intIndexintlength) { the intHead = 0; * intTail = length-1; $ if(index = = Head | | index = =tail) {Panax Notoginseng return1; - } the intRESULT1 = index-head; + intRESULT2 = Tail-index; A the intmin = result1 <= result2?result1:result2; + returnMin * 2 + 1; - } $ $ Private StaticString Getmaxstrbyindex (intIndexChar[] chars) { -StringBuilder SB =NewStringBuilder (string.valueof (Chars[index)); - intLength =chars.length; the intHead = Index-1; - intTail = index + 1;Wuyi the //Middle Deal - while(true) { Wu if(Head >= 0 && chars[index] = =Chars[head]) { -Sb.insert (0, string.valueof (chars[head--])); About}Else if(Tail <= length-1 && chars[index] = =Chars[tail]) { $Sb.append (String.valueof (chars[tail++])); -}Else { - Break; - } A } + the //besides deal - while(true) { $ if(Head < 0 | | tail > LENGTH-1) { the Break; the } the if(Head >= 0 && tail <= length-1 && chars[head] = =Chars[tail]) { theSb.insert (0, string.valueof (chars[head--])); -Sb.append (String.valueof (chars[tail++])); in Continue; the } the Break; About the } the returnsb.tostring (); the}View Code
2. DP Solution
Leetcode algorithm Collation