蓝桥杯 算法训练 字串统计

问题描述
  给定一个长度为n的字符串S,还有一个数字L,统计长度大于等于L的出现次数最多的子串(不同的出现可以相交),如果有多个,输出最长的,如果仍然有多个,输出第一次出现最早的。
输入格式
  第一行一个数字L。
  第二行是字符串S。
  L大于0,且不超过S的长度。
输出格式
  一行,题目要求的字符串。

  输入样例1:
  4
  bbaabbaaaaa

  输出样例1:
  bbaa

  输入样例2:
  2
  bbaabbaaaaa

  输出样例2:
  aa
数据规模和约定
  n<=60
  S中所有字符都是小写英文字母。
提示

  枚举所有可能的子串,统计出现次数,找出符合条件的那个

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
#define MAXSIZE 60  
int L;  
char s[MAXSIZE];  
int vi[MAXSIZE];  
  
void init()  
{  
    int i;  
    for(i = 0; i < MAXSIZE; i ++){  
        vi[i] = 1;  
    }  
}  
  
int countSame(int i, int len)  
{  
    int j, count;  
    char s1[MAXSIZE], s2[MAXSIZE];  
      
    count = 0;  
    strcpy(s1, s+i);  
    s1[len] = '\0';  
      
    for(j = i+1; j+len <= strlen(s); j ++){  
        if(! vi[j]){  
            continue;  
        }  
          
        strcpy(s2, s+j);  
        s2[len] = '\0';  
        if(strcmp(s1, s2) == 0){  
            count ++;  
            vi[j] = 0;  
        }  
          
    }  
      
    return count;  
}  
  
char *findStr()  
{  
    int i, l, tempLen, counTemp0, counTemp1, countStr;  
    char temp[MAXSIZE];  
    char *str = (char *)malloc(sizeof(char) * MAXSIZE);  
  
    l = strlen(s);  
    tempLen = L;  
    counTemp0 = counTemp1 = countStr = 0;  
      
    while(tempLen <= l){  
        init();  
        counTemp0 = counTemp1 = 0;  
          
        for(i = 0; i+tempLen <= l; i ++){  
            if(! vi[i]){  
                continue;  
            }  
              
            vi[i] = 0;  
            counTemp0 = countSame(i, tempLen);  
            if(counTemp0 > counTemp1){  
                counTemp1 = counTemp0;  
                strcpy(temp, s+i);  
                temp[tempLen] = '\0';  
            }  
        }  
              
        if(counTemp1 >= countStr){  
            countStr = counTemp1;  
            strcpy(str, temp);  
        }  
  
        tempLen ++;  
    }  
  
    return str;  
}  
  
int main()  
{  
    scanf("%d%s", &L, s);  
      
    char *theStr = findStr();  
      
    printf("%s",theStr);   
      
    free(theStr);  
      
    return 0;  
}  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值