找到字符串中出现最多的字符
找到字符串中出现最多的字符, 程序当然还是有很多缺陷程序代码:
/* 先统计, 再遍历*/ #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 编辑 ]