統計一個字符串中出現最多字符串的個數(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;
}

 

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