首页 > 学院 > 开发设计 > 正文

蓝桥杯算法训练——字符统计

2019-11-06 08:03:06
字体:
来源:转载
供稿:网友

问题描述   给定一个长度为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 <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#include <set>#include <cmath>#include <algorithm>#include <queue>#define INF 0x3f3f3f3f#define MAXN 10005#define Mod 10001using namespace std;struct node{ char str[100]; int len,cnt;};node a[MAXN];char s[100];int main(){ int l; scanf("%d",&l); scanf("%s",s); int lenth=strlen(s),num=0,d; for(int len=l;len<=lenth;++len) { for(int i=0;i+len<lenth;++i) { d=0; for(int j=i;j<i+len;++j) a[num].str[d++]=s[j]; a[num].cnt=1; a[num].len=d; num++; } } int maxcnt=-1,maxnum=num-1; for(int i=0;i<num;++i) { for(int j=i+1;j<num;++j) { if(strcmp(a[i].str,a[j].str)==0) { a[i].cnt++; if(a[i].cnt>maxcnt||(a[i].cnt==maxcnt&&a[i].len>a[maxnum].len)) { maxcnt=a[i].cnt; maxnum=i; } } } } PRintf("%s/n",a[maxnum].str); return 0;}
上一篇:思维

下一篇:代码重构

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表