已知字符串“aabbbcddddeeffffghijklmnopqrst”编程找出出现最多的字符和次数,要求时间复杂度小于O(n^2)
/********************************************************
Copyright (C), 2016-2017,
FileName: main9
Author: woniu201
Email: wangpengfei.201@163.com
Created: 2017/10/31
Description:求字符串中出现次数最多的字符和次数
********************************************************/
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void search(char* pData, int len)
{
char counts[1024] = {0}; //存放原始数据作为为索引出现的次数
char bufMax[1024] = {0}; //用于存放出现次数最多的字符
int max = 0; //出现次数最多的字符
for (int i=0; i<len; i++)
{
counts[pData[i]] ++;
}
for (int i=0; i<1024; i++)
{
if (counts[i] > max)
{
max = counts[i];
bufMax[0] = i;
}else if ((counts[i] == max) && (counts[i] !=0))
{
bufMax[strlen(bufMax)] = i;
}
}
printf("出现最多的字符分别为:");
for (int i=0; i<strlen(bufMax); i++)
{
printf("%c ", bufMax[i]);
}
printf("
");
printf("出现最多的字符的次数:%d
", max);
}
int main()
{
char* srcData = "aabbbcddddeeffffghijklmnopqrst";
search(srcData, strlen(srcData));
getchar();
return 1;
}
欢迎加群交流:C/C++开发交流