Question
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exist one unique longest palindromic substring.
Analysis and Solution
If a string is a return, the prefix and suffix centered on a character are the same. for example, if a text string "ABA" is centered on B, its prefix and suffix are the same.
Therefore, we can enumerate the central position, expand it to the left and right sides, record and update the retrieval length. The Code is as follows:
Strng longestpalidrome (string s) {int I, j, Max, C; max = 0; string ret; for (I = 0; I <S. size (); I ++) {for (j = 0; (I-j> = 0) & (I + j <n); j ++) {// assume that it is only an odd string, if (s [I-j]! = S [I + J]) break; C = J * 2 + 1;} If (C> MAX) {ret = S. substr (I-j + 1, C); max = C ;}for (j = 0; (I-j> = 0) & (I + J + 1 <n); j ++) {// assume this is an even string if (s [I-j]! = S [I + J + 1]) break; C = J * 2 + 2;} If (C> MAX) {ret = S. substr (I-j + 1, C); max = C;} return ret ;}
The time complexity is O (n ^ 2 ).
There is also an O (n) Time Complexity Algorithm on the Internet, more complex. can refer to: http://blog.csdn.net/feliciafay/article/details/16984031
Longest palindromic substring-leetcode