Longest Palindromic Substring -LeetCode

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.