求字串中重複出現的最長字串

來源:互聯網
上載者:User

求字串中重複出現的最長字串

例如字串:drgabcifrabcsdrrs中,最長公用字串是:abc

方法:利用尾碼樹來求。

字串的尾碼樹有如下:

drgabcifrabcsdrrs

rgabcifrabcsdrrs

gabcifrabcsdrrs

abcifrabcsdrrs---------s1

..............

rabcsdrrs

abcsdrrs-----------s2

...............

我們求的這些尾碼字串中,某2個串的最長公用首碼就是想要的答案。比如s1和s2的最長公用首碼:abc

我們為了簡化運算,講尾碼字串排序,這樣首碼相同的就會排在相鄰的位置上。

代碼如下:

#include<iostream>#include<string>using namespace std;int commonStr(string str1,string str2)//求兩個字串最長公用前置長度{    int len = (str1.length()>str2.length())?str2.length():str1.length();    int i=0;    while(i<len && str1[i]==str2[i])                i++;    return i;}void maxLen(string str,string &key)//求字串str的最長重複字串,key是用來存放首碼的{    int len = str.length();    string *sub= new string[len];//定義一個字串資料存放尾碼字串    for(int i=0;i<len;i++)    {            sub[i] = str.substr(i,len-i);    }    sort(sub,sub+len);//對尾碼字串進行排序    int max = 1;    for(int i = 1;i<len;i++)    {            int count = commonStr(sub[i],sub[i-1]);//計算相鄰的字串的公用前置長度            if(max<count)//如果當前長度大於最大長度,那麼更新max和key            {                         key = sub[i].substr(0,count);                         max = count;            }    }}int main(){    string str = "yyabcdabjcabcdg";    string key = "abc";    maxLen(str,key);    cout<<key<<endl;    getchar();    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.