算法训练 字串统计
时间限制:1.0s 内存限制:512.0MB
问题描述
给定一个长度为n的字符串S,还有一个数字L,统计长度大于等于L的出现次数最多的子串(不同的出现可以相交),如果有多个,输出最长的,如果仍然有多个,输出第一次出现最早的。
输入格式
第一行一个数字L。
第二行是字符串S。
L大于0,且不超过S的长度。
输出格式
一行,题目要求的字符串。
输入样例1:
4
bbaabbaaaaa
输出样例1:
bbaa
输入样例2:
2
bbaabbaaaaa
输出样例2:
aa
数据规模和约定
n<=60
S中所有字符都是小写英文字母。
提示
枚举所有可能的子串,统计出现次数,找出符合条件的那个
满分代码:
#include<iostream>
#include<map>
#include<vector>
using namespace std;
int main(){
map<string,int> Map;
map<string,int>::iterator it;
string str;
string ans;//记录输入结果
int max = 0;//记录出现次数
int lmax = 0;//记录长度
int l;
cin >> l >> str;
int i,j;
for(i = 0;i < str.length() - l + 1;i ++){
for(j = l;j <= str.length() - i;j ++){
string s = str.substr(i,j);
if(Map.find(s) == Map.end())
Map[s] = 1;
else
{
Map[s]++;
if(Map[s] > max){
max = Map[s];
lmax = s.length();
ans = s;
}
else if(Map[s] == max && s.length() > lmax){
ans = s;
lmax = s.length();
}
}
}
}
cout << ans;
return 0;
}