算法训练 字串统计
题目描述:
给定一个长度为n的字符串S,还有一个数字L,统计长度大于等于L的出现次数最多的子串(不同的出现可以相交),如果有多个,输出最长的,如果仍然有多个,输出第一次出现最早的。
输入描述:
第一行一个数字L。
第二行是字符串S。
L大于0,且不超过S的长度。
输出描述:
一行,题目要求的字符串。
输入样例:
4
bbaabbaaaaa
输出样例:
bbaa
测试代码:
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 5 using std::cin; 6 using std::cout; 7 using std::endl; 8 using std::string; 9 using std::vector; 10 using std::find; 11 12 string GetStrCount(int L, string S) 13 { 14 int len = S.length(); 15 vector<string> vec; 16 for (int i = L; i <= len; i++) 17 { 18 for (int j = 0; j <= len - i; j++) 19 { 20 vec.push_back(S.substr(j, i)); 21 } 22 } 23 24 vector<int> book(vec.size()); 25 for (int i = 0; i < vec.size() - 1; i++) 26 { 27 for (int j = 0; j < vec.size(); j++) 28 { 29 if (i != j && vec.at(i) == vec.at(j)) 30 { 31 book[i]++; 32 } 33 } 34 } 35 36 int max = -1; 37 int k = 0; 38 for (int i = 0; i < book.size() - 1; i++) 39 { 40 if (book.at(i) > max || (book.at(i) == max && vec.at(k).length() < vec.at(i).length())) 41 { 42 k = i; 43 max = book.at(i); 44 } 45 } 46 return vec.at(k); 47 } 48 49 int main(void) 50 { 51 int L; 52 string S; 53 54 cin >> L; 55 cin >> S; 56 57 string str = GetStrCount(L, S); 58 59 cout << str << endl; 60 61 return 0; 62 }