C++
使用hash map存储每个子串出现的次数
1 #include <iostream> 2 #include <vector> 3 #include <unordered_map> 4 using namespace std; 5 6 pair<int, string> fun(const string& str) { 7 int len = str.length(); 8 if (len == 0){ 9 return make_pair(0,string("")); 10 } 11 unordered_map<string, int> map(len*len); 12 13 pair<int, string> ret = make_pair(1, str.substr(0,1)); 14 15 for (int i = 0; i < len; ++i) { 16 for (int j = 1; j < len - i + 1; ++j) { 17 string substr = str.substr(i,j); 18 if (map.find(substr) == map.end()) { 19 map[substr] = 1; 20 } else { 21 map[substr] += 1; 22 if (map[substr] > ret.first) { 23 ret = make_pair(map[substr], substr); 24 } else if (map[substr] == ret.first && substr.length() > ret.second.length()) { 25 ret = make_pair(map[substr], substr); 26 } 27 } 28 } 29 } 30 return ret; 31 }; 32 int main() 33 { 34 string str = "zhanghaeha"; 35 pair<int, string> rs = fun(str); 36 cout<<rs.second<<":"<<rs.first<<endl; 37 return 0; 38 }
本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5010973.html,如需转载请自行联系原作者