如题,如何在一亿位整数组成的字符串中找到出现次数最多的递增数字串?
1亿个字符串占用的缓存超出了编译器的默认缓存,所以我代码中定义了一个宏来表示字符串的最大长度,如果你需要扩展到1亿,需要修改编译器的默认缓存大小,然后把宏定义的值调大即可。代码如下,如有帮助,请采纳一下,谢谢。
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100000
int main()
{
char buf[MAX_SIZE] = {0};
int i = 0,len = 0,index = 0;
char maxbuf[12] = {0}; //最大的可能是0-9,最多10个字符,12个空间足够用
char maxbuf2[12] = {0};
int maxlen = 0;
gets(buf); //实际字符串由外部输入,或者从文件读取,这个根据实际情况修改吧
len = strlen(buf); //获取实际长度
maxbuf2[0] = buf[0];
i = 1;
index = 1;
while(i < len)
{
if (buf[i] > buf[i-1])
{
maxbuf2[index] = buf[i];
index++;
}else
{
if (index > maxlen)
{
maxlen = index;
strcpy(maxbuf,maxbuf2);
maxbuf[index] = '\0';
maxbuf2[0] = buf[i];
index = 1;
}else
{
maxbuf2[0] = buf[i];
index = 1;
}
}
i++;
}
//处理最后一个串
if (index > maxlen)
{
maxlen = index;
strcpy(maxbuf,maxbuf2);
maxbuf[index] = '\0';
}
printf("最大串长度:%d,字符串:%s\n",maxlen,maxbuf);
return 0;
}
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100000
//buf是存储文件的缓冲区,lSize是文件大小
void textFileRead(char* filename,char buf[],int *lSize)
{
FILE *pf = fopen(filename,"r");
fseek(pf,0,SEEK_END);
*lSize = ftell(pf);
// 用完后需要将内存free掉
rewind(pf);
*lSize = fread(buf,sizeof(char),*lSize,pf);
buf[*lSize] = '\0';
}
int main()
{
char buf[MAX_SIZE] = {0};
int i = 0,len = 0,index = 0;
char maxbuf[12] = {0}; //最大的可能是0-9,最多10个字符,12个空间足够用
char maxbuf2[12] = {0};
int maxlen = 0;
textFileRead("F://abc.txt",buf,&len);
//gets(buf); //实际字符串由外部输入,或者从文件读取,这个根据实际情况修改吧
//len = strlen(buf); //获取实际长度
maxbuf2[0] = buf[0];
i = 1;
index = 1;
while(i < len)
{
if (buf[i] > buf[i-1])
{
maxbuf2[index] = buf[i];
index++;
}else
{
if (index > maxlen)
{
maxlen = index;
strcpy(maxbuf,maxbuf2);
maxbuf[index] = '\0';
maxbuf2[0] = buf[i];
index = 1;
}else
{
maxbuf2[0] = buf[i];
index = 1;
}
}
i++;
}
//处理最后一个串
if (index > maxlen)
{
maxlen = index;
strcpy(maxbuf,maxbuf2);
maxbuf[index] = '\0';
}
printf("最大串长度:%d,字符串:%s\n",maxlen,maxbuf);
return 0;
}