最長重複子串

來源:互聯網
上載者:User

http://blog.csdn.net/huang12315/article/details/6455090

int getNext(char *str,int *next){int len=strlen(str);int index=0;int k=-1;next[0]=k;int max=0;//kmp演算法求next值,取得最大的字串while (index<len){if (k==-1 || str[index]==str[k]){k++;index++;next[index]=k;if (k>max)//求得其中重複最大的字串的個數,也就是與最前面串的重複數{max=k;}}elsek=next[k];}return max;}int main(){char str[50];//輸入字串cin>>str;int max=0;//最大的字串int nextMax;//接受getNext函數中返回的最大值int index;int maxIndex;//儲存最大的字串起始位置int len=strlen(str);//將一個字串從開始一直減少到只剩一個字元,通過這個取得最小字串for (index=0;index<len-1;index++){int *next=new int[len-index];//取得next在這沒用nextMax=getNext(str+index,next);//每次從str+index開始if (nextMax>max){max=nextMax;maxIndex=index;}}//輸出最長字串cout<<"最長字串: ";for (index=0;index<max;index++){cout<<str[index+maxIndex];}cout<<endl;return 0;}

通過將一個字串分成n-1個子串,每次通過kmp演算法取得字串的next值,從而算出該子串的最長重複子串,儲存最大的,就可得答案

其中getNext函數只能取得的是這個子串中後面的子串與開始子串的重複數,所以通過這個思路將一個長的字串分解為n-1個子串即可

聯繫我們

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