题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
class Solution { public: int getLongestPalindrome(string A, int n) { int m=1; for(int i=0; i<n; i++) for(int j=n-1; j>i; j--) { if(A[i]==A[j]) { int t1=i,t2=j; while(t1<n&&A[t1]==A[t2]) { if(t1<t2) { t1++; t2--; continue; } if(t1==t2) m=max(m,(j-t2)*2+1); else if(t1>t2) m=max(m,(j-t2)*2); break; } } } return m; } };
class Solution { public: int getLongestPalindrome(string A, int n) { int m=1; //中间向两边展开 for(int i=1; i<n; i++) { int j=1;//j为移动的位数 while(i-j>=0&&i+j<=n&&A[i-j]==A[i+j])//121 j++; m=max(m,j*2-1); j=0; while(i-j>=0&&i+j<=n&&A[i-j]==A[i+j-1])//11 j++; m=max(m,j*2-2); } return m; } };