標籤:style blog http color os ar for div art
題目
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.
分析與解法
如果一段字串是迴文,那麼以某個字元為中心的首碼和尾碼都是相同的.例如,一段迴文串"aba",以b為中心,它的首碼與尾碼都是相同的.
因此,我們可以枚舉中心位置,然後在該位置上向左右兩邊擴充,記錄並更新得到的迴文長度.代碼如下:
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++){ //假設只是奇數形式的字串 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++){ //假設這是偶數形式的字串 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;}
它們分別對於以i中心的,長度為奇數與偶數的兩種情況.時間複雜度為O(n^2).
在網上還有一種O(N)時間複雜度的演算法,比較複雜.可以參考:http://blog.csdn.net/feliciafay/article/details/16984031
Longest Palindromic Substring -LeetCode