这类题型,很直观,,求思路,求解析~~~
用直方图表示字符中每个字母出现的次数。(忽略大小写字母)例输入:Intel's chips have been running hotter.
显示A B C E G H I L N O P R S T U V
| |
| |
| | | | |
| | | | | | |
| | | | | | | | | | | | | | | |
/* cosdos 2011-06-15 */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> // for tolower() #define ALPHA_COUNT 26 void print(int *ar) { int i, line; // 计算行数,并打印列标题。 for (line=i=0; i < ALPHA_COUNT; ++i) { if (ar[i]) { printf("%c ", toupper('a'+i)); line = (ar[i]>line ? ar[i] : line); } } putchar('\n'); // 根据行数和字母数量打印列。 for (line; line >= 1; --line) { for (i=0; i < ALPHA_COUNT; ++i) { if (ar[i]>0) { printf("%c ", (ar[i]>=line ? '|' : ' ') ); } } putchar('\n'); } } int main(void) { int i, ch; int alpar[ALPHA_COUNT]={0}; while ('\n' != (ch=getchar()) && EOF != ch) { if (isalpha(ch)) { ++alpar[ tolower(ch) - 'a' ]; //printf("%c:%d ", toupper(ch), alpar[tolower(ch) - 'a']); } } print(alpar); system("pause"); return 0; }
#include <stdio.h> #include <ctype.h> #define STR_FRE_LENGTH 51 #define CHAR_LENGTH 26 #define set1(index, array) \ array |= 1 << index; #define set0(index, array) \ array &= ~(1 << index); typedef struct { unsigned times; char value; } Character; int get(int index, unsigned value) { return (value & (1 << index)) >> index; } void init_characters(Character * chars) { int i; for(i = 0; i < CHAR_LENGTH; i++) { chars[i].times = 0; chars[i].value = i + 'a'; } } int max_times(Character * chars) { int i, max = chars[0].times; for(i = 1; i < CHAR_LENGTH; i++) max < chars[i].times && (max = chars[i].times); return max; } void addition(Character * chars, char ch) { if(islower(ch)) chars[ch - 'a'].times++; else if(isupper(ch)) chars[ch - 'A'].times++; } int main(void) { int i, j, k, max; char str[STR_FRE_LENGTH], * p = str; unsigned fre[STR_FRE_LENGTH - 1] = {0}; Character chars[CHAR_LENGTH]; init_characters(chars); gets(str); while(*p) addition(chars, *p++); max = max_times(chars); for(i = 0; i < CHAR_LENGTH; i++) chars[i].times && printf("%-2c", chars[i].value); printf("\n"); for(i = max, k = 0; i > 0; i--, k++) for(j = 0; j < CHAR_LENGTH; j++) if(chars[j].times >= i) set1(j, fre[k]); for(i = 0; i < max; i++) { for(j = 0; j < CHAR_LENGTH; j++) { get(j, fre[i]) && printf("%-2c", '|'); !get(j, fre[i]) && chars[j].times && printf("%-2c", ' '); } printf("\n"); } return 0; }