统计一个字符串中出现最多字符串的个数(2019秋招360笔试题)

/*
看到网上用后缀数组法求子串最多,但是亲测不行,有的数据通过不了。
然后自己想了一个,先将所有可能出现字符串全部分割保存,然后将对应字符串
按照字符串的大小放到相应数组中,然后比较找最大的。
单纯对题目而言的话实际不用这模麻烦,(后来才自己想明白),求子串重复最大个数,完全
可以求最大出现字符个数,因为子串是由单个字符组成。如果子串最大,当然里面字符也是最多
的。
*/

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#define max(a,b) a>b?a:b

using namespace std;

int main()
{
	int Max = -1;//定义输出最大值
	string str;
	vector<vector<string>>tmp;//将字符分割开,全部放入tmp中
	cin >> str;
	for (int i = 0; i < str.length(); i++)
	{
		vector<string>cmp;
		string s = str.substr(i);
		for (int j = 1; j <= s.length(); j++)
		{
			string s1 = s.substr(0, j);
			cmp.push_back(s1);
		}
		tmp.push_back(cmp);
	}
	vector<vector<string>>cnp(str.length()+1);//将所有分割字符按照个数分别放入指定框中
	for (int i = 0; i < tmp.size(); i++)
	{
		for (int j = 0; j < tmp[i].size(); j++)
		{
			cnp[tmp[i][j].length()].push_back(tmp[i][j]);
		}
	}
	for (int i = 1; i < cnp.size(); i++)//找出最多的子串数。
	{
		int cnt = 1;
		sort(cnp[i].begin(), cnp[i].end());
		for (int j = 1; j < cnp[i].size(); j++)
		{
			if (cnp[i][j] == cnp[i][j - 1])
				cnt++;
			else
			{
				Max = max(Max, cnt);
				cnt = 1;
			}
		}
	}
	cout << Max << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章