最長迴文子串(manacher演算法實現)

來源:互聯網
上載者:User

#include<iostream>
using namespace std;
#define M 1000

void Manacher(char *str,char*maxpalindrome )//str接受原始字串  maxpalindrome儲存最長迴文子串
{

 int i,j;
 int maxrad=0,position=0;//記錄最長迴文半徑和出現最長迴文半徑的地方
    int mx = 0, id;//id出現最長延伸位置的字元位置,向右延伸到的最遠位置
 char temp[2*M+2];//用於儲存處理後的字串
 int rad[M];//迴文半徑數組
 int length =strlen(str);
    int num=2*strlen(str)+2;//記錄插入字元後的字串長度
  
 
 
 //處理原始字串
 temp[0]='$';
 for(i=0;i<=length;i++)
 {
   temp[2*i+1]='#';
   temp[2*i+2]=str[i];
 }
 
 cout<<temp<<endl;
 
 
 
 
 
 //計算迴文半徑數組
    for(i=1; i<num; i++)
    {
        if( mx > i )
   rad[i] = rad[2*id-i]<(mx-i)?rad[2*id-i]:(mx-i);       
        else
            rad[i] = 1;//迴文半徑至少是1
        for(; temp[i+rad[i]] == temp[i-rad[i]]; rad[i]++);//找到最大迴文半徑

        if( rad[i] + i > mx )//向右延伸位置大於了前一個字元的迴文串的向右最大延伸位置 重新整理最大延伸位置
        {
            mx = rad[i] + i-1;//記錄新的延伸位置 延伸位置是從1開始的
            id = i;//記錄出現最長延伸字元的位置
        }
    }

 
 
 
 for(i=1;i<num;i++)//找到最大迴文半徑及出現最大迴文半徑的地方
  {
   if(rad[i]>maxrad)
   {
  maxrad=rad[i];//記錄最大迴文半徑
  position=i;//記錄出現最大迴文半徑的地方
   }
  }

 

 

    //根據迴文半徑和出現最大迴文半徑的位置,把最長迴文子串拷貝出來
 for(i=0,j=position-maxrad+1;j<position+maxrad-1;j++)
 {
  
  if(temp[j]!='#'&&temp[j]!='$')
  {
  maxpalindrome[i]=temp[j];
   i++;
  }
 
  
  
 
 }
 maxpalindrome[i]='\0';

 

}

int main()
{
 char str[]="gdabebajuk";
    char maxpalindrome[M];
  Manacher(str,maxpalindrome);
  cout<<maxpalindrome<<endl;
  return 0;
 

 

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.