题目描述
度度熊收到了一个只有小写字母的字符串S,他对S的子串产生了兴趣,S的子串为S中任意连续的一段。他发现,一些子串只由一种字母构成,他想知道在S中一共有多少种这样的子串。
例如在串”aaabbaa”中,度度熊想找的子串有”a”,”aa”,”aaa”,”b”,”bb”五种。
(本题只考虑子串的种数,相同的子串在多个位置出现只算一次)
使用C++ map加KMP find函数解决
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
string str;
map<char, int> mp;
cin >> str;
for (auto s : str) {
mp[s]++;
}
int res = 0;
for (auto it = mp.begin(); it != mp.end(); ++it) {
string temp = "";
for (int i = 0; i < it->second; i++) {
temp += it->first;
if (str.find(temp) == -1)
break;
else res++;
}
}
cout << res << endl;
}