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.
The longest palindrome, for each character from the middle to the sides of the search, attention to the odd and even two kinds of cases. The total time complexity is O (n^2). In addition Manacher algorithm complexity is O (n), the manacher algorithm is very complex appearance, IQ catch urgent, have to digest a bit. Put on a simple one first.
1 classSolution {2 Public:3 intGetlps (Const string&s,intIDX1,intidx2) {4 while(Idx1 >=0&& idx2 < S.length () && s[idx1] = =S[IDX2]) {5--idx1;6++idx2;7 }8 returnIDX2-IDX1-1;9 }Ten One stringLongestpalindrome (strings) { A if(S.length () <2)returns; - intLPS =-1, Lps1, LPS2, POS; - for(inti =0; I < s.length (); ++i) { theLPS1 =Getlps (S, I, I); -LPS2 = Getlps (s, I, i +1); - if(Lps1 > LPs | | lps2 >LPs) { -pos =i; +LPS =Max (LPS1, LPS2); - } + } A if(LPs &0x1)returnS.substr (pos-(lps-1)/2, LPs); at Else returnS.substr (pos-(lps-2)/2, LPs); - } -};
[Leetcode] Longest palindromic Substring