用C++写一个寻找字符串里重复最多的字符串的代码
时间: 2024-03-23 15:36:38 浏览: 16
可以使用 map 也就是哈希表来实现:
```cpp
#include <iostream>
#include <string>
#include <map>
using namespace std;
string find_most_common_string(string s) {
map<string, int> mp;
for (int i = 0; i < s.size(); i++) {
for (int j = i+1; j <= s.size(); j++) {
string sub_str = s.substr(i, j-i);
mp[sub_str]++;
}
}
int max_count = 0;
string max_str = "";
for (auto it = mp.begin(); it != mp.end(); it++) {
if (it->second > max_count) {
max_count = it->second;
max_str = it->first;
}
}
return max_str;
}
int main() {
string s = "abbcccddddeeeeeffffff";
string res = find_most_common_string(s);
cout << res << endl;
return 0;
}
```
该代码接收一个字符串作为参数,使用两层嵌套循环遍历所有子串,并将子串作为键存储在 map 中,出现次数为值。最后遍历 map,找到出现次数最多的子串,返回该子串即可。
需要注意的是,map 是自动排序的,因此不需要再手动排序,直接遍历即可。