写代码是一种艺术,甚于蒙娜丽莎的微笑!

不拼搏,枉少年!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

举个例子说明一下:例如找到字符串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

posted on 2016-05-13 11:08  RunningSnail  阅读(3354)  评论(0编辑  收藏  举报