20140606 连续出现次数最多的子串

本文介绍了一种用于寻找字符串中最长重复子串的算法实现。通过遍历所有可能的子串并计数来找出重复次数最多的子串及其出现频率。此算法适用于文本处理等领域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、求一串字符串中连续出现次数最多的字串

#include<iostream>
#include<string>
#include<vector>
using namespace std;
pair<int,string> fun(const string &str)
{
    vector<string> substrs;   
    int maxcount=1,count=1;
    string substr;
    int i,len=str.length();
    for(i=0;i<len;++i)
        substrs.push_back(str.substr(i,len-i));  //str="abcbcbcabc",那么substrs如下所示
        /*    a    b    c    b    c    b    c    a    b    c    substrs[0]
                  b    c    b    c    b    c    a    b    c    substrs[1]
                       c    b    c    b    c    a    b    c    substrs[2]
                            b    c    b    c    a    b    c    substrs[3]
                                 c    b    c    a    b    c    substrs[4]
                                      b    c    a    b    c    substrs[5]
                                           c    a    b    c    substrs[6]
                                                a    b    c    substrs[7]
                                                     b    c    substrs[8]
                                                          c    substrs[9]
                                                */

    for(i=0;i<len;i++)//扫描substrs的十个元素,每次扫描一个,总共10次(*处)   
    {
        for(int j=i+1;j<len;++j)//针对substrs的某个元素,扫描步长从1到len-1
        {
            count=1;
            if(substrs[i].substr(0,j-i)==substrs[j].substr(0,j-i))//比较字符串substrs[i]的前j-i个字符和从substrs[j]的前j-i个字符是否相同。开始的字符是否相同, 如abcabcbc(i=0,j=3时) .
            {
                ++count;
                for(int k=j+(j-i);k<len;k+=j-i)     
                {
                    if(substrs[i].substr(0,j-i)==substrs[k].substr(0,j-i))
                        ++count;
                    else
                        break;
                }
                if(count>maxcount)
                {    
                    maxcount=count;
                    substr=substrs[i].substr(0,j-i);
                }
            }
        }
    }
    return make_pair(maxcount,substr);
}

int main()
{
    string str;
    pair<int,string> rs;
    while(cin>>str)
    {
        rs=fun(str);
        cout<<rs.second<<':'<<rs.first<<'\n';
    }
    return 0;
}
i=0时。
i=1时。

2、从今天开始晚上不吃东西了。确定,一定,以及肯定,锻炼身体

转载于:https://www.cnblogs.com/yexuannan/p/3773676.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值