#2
qhanchen2012-10-07 17:28
|
程序代码:
/* 先统计, 再遍历*/
#include <stdio.h>
#include <stdlib.h>
#define NO_OF_CHARS 256
int *getCharCountArray(char *);
char getIndexOfMax( int *, int);
char getMaxOccuringChar(char *str);
int main(void) {
char str[] = "sample string";
printf("%c\n", getMaxOccuringChar(str));
return 0;
}
char getMaxOccuringChar(char *str) {
int *count = getCharCountArray(str);
return getIndexOfMax(count, NO_OF_CHARS);
}
int *getCharCountArray(char *str) {
int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));
int i;
for(i = 0; *(str+i); i++)
count[*(str+i)]++;
return count;
}
char getIndexOfMax(int ar[], int ar_size) {
int i;
int max_index = 0;
for( i = 1; i < ar_size; i++)
if(ar[i] > ar[max_index])
max_index = i;
free(ar);
ar = NULL;
return max_index;
}
#include <stdio.h>
#include <stdlib.h>
#define NO_OF_CHARS 256
int *getCharCountArray(char *);
char getIndexOfMax( int *, int);
char getMaxOccuringChar(char *str);
int main(void) {
char str[] = "sample string";
printf("%c\n", getMaxOccuringChar(str));
return 0;
}
char getMaxOccuringChar(char *str) {
int *count = getCharCountArray(str);
return getIndexOfMax(count, NO_OF_CHARS);
}
int *getCharCountArray(char *str) {
int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));
int i;
for(i = 0; *(str+i); i++)
count[*(str+i)]++;
return count;
}
char getIndexOfMax(int ar[], int ar_size) {
int i;
int max_index = 0;
for( i = 1; i < ar_size; i++)
if(ar[i] > ar[max_index])
max_index = i;
free(ar);
ar = NULL;
return max_index;
}
[ 本帖最后由 madfrogme 于 2012-10-7 18:33 编辑 ]