第二行是字符串S。
L大于0,且不超过S的长度。
输入样例1:
4
bbaabbaaaaa
输出样例1:
bbaa
输入样例2:
2
bbaabbaaaaa
输出样例2:
aa
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;
}