• 求一个字符串中连续出现次数最多的子串


    举个例子说明一下:例如找到字符串mainStr="abcabcabcde"中连续出现次数最多的子串,可以看出"abc"出现3次,是出现次数最多的子串。对于该题可以用穷举法,一一列举每个子串连续出现的最大次数。

    如下图1,对于每一个子串都从当前位置i=pos1(子串开始位置)进行遍历,其中j=pos2为子串结束的位置。那么offset=pos2-pos1即为当前子串的长度,如果mainStr.substr(i,offset) == mainStr.substr(j,offset)则按照该offset偏移量从k=pos2+offset处开始遍历,每次增加offset个长度直至字符串结尾。当mainStr.substr(i,offset) == mainStr.substr(k,offset)时,表示出现连续相同的子串,否则break跳出当前循环。继续从j+1位置处继续循环执行。

    看代码:

    void findMaxSubStr(const string& mainStr, string& maxSubStr,int &maxCounts)
    {
        int len = mainStr.length();
        for (int i = 0; i < len; i++)
        {
            for (int j = i + 1; j < len; j++)
            {
                int counts = 1;
                int offset = j - i;
                if (mainStr.substr(i, offset) == mainStr.substr(j, offset))
                {
                    counts++;
                }
                else
                    continue;
                for (int k = j + offset; k < len; k += offset)
                {
                    if (mainStr.substr(i, offset) == mainStr.substr(k, offset))
                    {
                        counts++;
                    }
                    else
                        break;
                }
    
                if (maxCounts < counts)
                {
                    maxCounts = counts;
                    maxSubStr = mainStr.substr(i, offset);
                }
            }
        }
    }

    图1

  • 相关阅读:
    redis应用场景之文章投票设计思路
    Redis存储的5种数据结构
    v+=e 不等价于 v=v+e
    WebMagic
    指针函数和函数指针的区别
    为什么说StringBuilder不安全?
    sql注入
    Autowired报错处理
    SpringBoot入门最简单的一个项目示例
    MVC中Cookie的用法(二)---CookieHelper
  • 原文地址:https://www.cnblogs.com/tgycoder/p/5488687.html
Copyright © 2020-2023  润新知