藍橋杯試題 算法訓練 字串統計

藍橋杯試題 算法訓練 字串統計

題目描述:

資源限制
時間限制: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中所有字符都是小寫英文字母。
提示
  枚舉所有可能的子串,統計出現次數,找出符合條件的那個

解題思路:
如提示,找到所有的子串(長度≥L),再去暴力統計子串出現次數。

AC代碼:

#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 10001
using namespace std;
struct node
{
    char str[100];
    int len,cnt;
}a[MAXN];
char s[100];
int main()
{
    int l;
    scanf("%d",&l);
    scanf("%s",s);//aaaabaaaa
    int lenth=strlen(s),num=0,d;
    for(int len=l;len<=lenth;len++)//統計長度大於等於l(len)的出現次數最多的子串
    {
        for(int i=0;i+len<=lenth;i++)//注意這裏i的值的遍歷(子串的第一個索引位置的遍歷),i的最大值爲lenth-len【可以等於lenth-len】
        {
            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++;
        }
    }
//    for(int i=0;i<num;i++)
//		cout<<a[i].str<<endl; 
    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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章