N為一個substring的長度,找出題目string裡面哪個substring重複最多次數。
想法:
用map[substring] = 次數 來記錄每個substring出現的次數,然後再找出最大的次數並輸出該substring。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <map> | |
using namespace std; | |
int main() | |
{ | |
ios::sync_with_stdio(false); | |
int N; | |
string str; | |
while (cin >> N) { | |
cin.get(); | |
getline(cin, str); | |
map<string, int> Map; | |
for (int i = 0; i <= str.size()-N; ++i) { | |
string tmp = str.substr(i, N); // 從第i個位置擷取str N個字元 | |
if (!Map[tmp]) Map[tmp] = 1; | |
else Map[tmp]++; | |
} | |
int Max = 0; | |
for (auto &m : Map) { // m為pair structure | |
if (m.second > Max) { | |
Max = m.second; | |
str = m.first; | |
} | |
} | |
cout << str << endl; | |
} | |
return 0; | |
} |
沒有留言:
張貼留言