求字符串中出現次數最多的子串及其出現次數


題目描述:

求字符串中出現次數最多的子串的出現次數。
例如字符串abcbcbcabc,出現次數最多的子串是bc,出現次數為4

思路:利用后綴數組:

abcbcbcabc    第0個
bcbcbcabc    第1個
cbcbcabc    第2個
bcbcabc    第3個
cbcabc    第4個
bcabc    第5個
cabc    第6個
abc    第7個
bc    第8個
c    第9個

過程:先從第0個數組取出a,然后和第1個數組的b比較,發現不相等,然后取ab,abc,abcb....這一趟取完后,又從第1個后綴數組開始取,取b,bc,bcb,bcbc...

#include<iostream>
#include<string>
#include<vector>

using namespace std;

pair<int, string> fun(const string &str)
{
	vector<string> substrs;
	int len = str.length();

	string substring;
	int maxcount(0);
	//后綴數組
	cout << "the string is:" << str << endl;
	cout << "the substrings are as follows:" << endl;
	for (int i = 0; i < len; ++i)
	{
		substrs.push_back(str.substr(i));
		cout << substrs[i] << endl;
	}

	cout << "--------------the answer------------" << endl;

	for (int i = 0; i < len; ++i)
	{
		for (int j = 1; j <= len; j++) {
			int count = 1;
			int sublen = j;
			for (int k = i + 1; k < len; k++) {
				
				if (substrs[k].length() < sublen) {
					break;
				}
				//cout << substrs[i].substr(0, sublen) << endl;
				//cout << substrs[k].substr(0, sublen) << endl;
				string str1 = substrs[i].substr(0, sublen);
				string str2 = substrs[k].substr(0, sublen);
				//cout << "比較結果:" << str1.compare(str2) << endl;
				//cout << "i = " << i << "  sublen = " << j << "  k = " << k << endl;
				if (str1.compare(str2)==0)
				{
					++count;
				}
				//cout << "count = " << count << endl;
			}
			if (count > maxcount||(count == maxcount && sublen > substring.length()))
			{
				maxcount = count;
				substring = substrs[i].substr(0, sublen);
			}
		}
	}

	return make_pair(maxcount, substring);

}


int main()
{
	string str = "ababcababcabcab";
	auto res = fun(str);

	cout << "the max count is:" << res.first << endl;
	cout << "the matched substring is:" << res.second << endl;
	return 0;
}

輸出:

the string is:ababcababcabcab
the substrings are as follows:
ababcababcabcab
babcababcabcab
abcababcabcab
bcababcabcab
cababcabcab
ababcabcab
babcabcab
abcabcab
bcabcab
cabcab
abcab
bcab
cab
ab
b
--------------the answer------------
the max count is:6
the matched substring is:ab

參考資料:

[1] 求一個字符串中連續出現次數最多的子串 https://blog.csdn.net/qq_22080999/article/details/81143555
[2] 【算法刷題】一個字符串中連續出現次數最多的子串 https://blog.csdn.net/Neo_dot/article/details/80559744


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM