首页 > 代码库 > C++实现在一个字符串中寻找最大子串

C++实现在一个字符串中寻找最大子串

//#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<utility>
using namespace std;
pair<int ,string> fun(const string &s)
{
	vector<string> substrs;
	string substr;
	int length=s.length();
	for(int i=0;i<length;++i)
	{
		substrs.push_back(s.substr(i,length-i));
		
	}
	cout<<"后缀子串分别为"<<endl;
	for(vector<string>::size_type index=0;index!=substrs.size();++index)
		cout<<substrs[index]<<endl;
	int count=0,maxcount=0;
	for(int i=0;i<length;++i)
	{
		for(int j=i+1;j<length;++j)
		{   count=1;
			if(substrs[i].substr(0,j)==substrs[j].substr(0,j))
			{
				++count;
				for(int k=j+(j-i);k<length;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 s("abcbcbcabc");
    pair<int,string> pair;
	pair=fun(s);
	cout<<pair.second<<" "<<pair.first<<endl;

	system("pause");
	return 0;
}

C++实现在一个字符串中寻找最大子串