找出所有最長連續重複子串及其個數

來源:互聯網
上載者:User

標籤:演算法

問題描述:
找出字串中所以最長連續重複子串及其個數
比如:
輸入:123234,最大連續重複字串為23,個數為2
輸入:5555,最大連續重複字串為555,個數為2
輸入:aaabbb 最大連續重複字串為aa,個數為2;和bb,個數為2
必須存在重複的字串才算,只出現一次的不算。可能存在多個相同長度的不同字串,比如aaabbb。

解題思路

與[求一個字串中連續出現次數最多的子串]的區別體現在兩個方面:一是要找最長子串(重複次數大於等於2即可);二是要考慮子串是有重疊的重複,如eeee的最長子串為eee。在上一題中, 有重疊的肯定不是連續出現次數最多的。

實現代碼
#include <iostream>#include <cstring>#include <utility>#include <string>#include <vector>using namespace std;vector<pair<int, string>> fun(const string& str){    vector<string> subs;    vector<pair<int, string>> res;    int len = str.size();    for (int i = 0; i < len; i++)    {        subs.push_back(str.substr(i));    }    int count = 1;    int maxCount = 1;    int subLen = 1;    string sub;    //i為子串的長度    for (int i = 1; i < len; i++)    {        for (int j = 0; j < len - 1; j++)        {            count = 1;            for (int k = j + 1; k <= j + i && subs[k].size() >= i; k++)            {                if (subs[k].substr(0, i) == subs[j].substr(0, i))                {                    count++;                    break;                }            }            if (count >= 2)            {                if (i > subLen)                {                    res.clear();                }                subLen = i;                maxCount = count;                sub = subs[j].substr(0, i);                res.push_back(make_pair(maxCount, sub));            }        }    }    return res;}int main(){    string str;    vector<pair<int, string>> res;    while (cin>>str)    {        res = fun(str);        for (auto it = res.begin(); it != res.end(); it++)        {            cout<<it->second<<":"<<it->first<<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.