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

这篇博客探讨了如何找到一个字符串内连续出现次数最频繁的子串。通过提供的代码,作者展示了利用C++或其他编程语言实现这一功能的方法。

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

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

代码如下:以后用size_t

// LongestCommonString.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

class LongestCommonString
{
	vector<string> suffixArray;
	size_t len;
public:

	//构造方法
	LongestCommonString(string s)
	{
		//构造后缀数组
		for(size_t i = 0; i < s.length(); ++i)
		{
			suffixArray.push_back(s.substr(i));
		}
		//排序
		sort(suffixArray.begin(), suffixArray.end());
		len = suffixArray.size();
	}

	//两两比较,返回最长长度的子串
	string lcpCompare()
	{
		size_t maxLength = 0;
		size_t index = 0;
		for(size_t i = 0; i < len - 1; ++i)
		{
			size_t temp = lcp(suffixArray.at(i), suffixArray.at(i+1));
			if(temp > maxLength)
			{
				maxLength = temp;
				index = i;
			}
		}
		return suffixArray.at(index).substr(0, maxLength);
	}

	//返回重复的长度
	size_t lcp(const string& a, const string& b)
	{
		size_t i = 0;
		while(a[i] == b[i])
		{
			++i;
		}
		return i;
	}
};

int main()
{
	//string h = "hello";
	//cout << h.substr(2, 3);
	string word = "aacaagmtttacaagmc";
	LongestCommonString slcp(word);
	cout << "最长重复子串为:" << slcp.lcpCompare() << endl;

	system("pause");
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值