最最开始的时候,想着用if,每个字母,每个字母地去统计,后来发现,速度太慢了,而且要写很多行,就像下面的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
#include<stdio.h> #include<string.h> int main() { int T; scanf("%d", &T); while(T --) { char s[2000]; char c; scanf("%s", s); int len, i, max = -1; len = strlen(s); for(i = 0; i < len; i ++) { int a=b=c=d=e=f=g=h=i=j=k=l=m=n=o=p=q=r=s=t=u=v=w=x=y=z=0; if(s[i] == 'a') { a ++; if(a > max) { max = a; c = 'a'; } } else if(s[i] == 'b') { b ++; if(b > max) { max = b; c = 'b'; } } else if(s[i] == 'c') { c ++; if(c > max) { max = c; c = 'c'; } } else if(s[i] == 'd') { d ++; if(d > max) { max = d; c = 'd'; } } } } return 0; } |
后来又仔细想了想,换了个角度。
1.先给所有的字符排序;
2.利用每个字符与ASCII码的对应关系,用一个数组来记录每个字母的个数。a的下标代表字母的ASCII码,a[i]则代表字母的个数;
3.寻找里面个数最多的字母,用到了max(记录出现次数最多字母的个数),flag(记录出现次数最多字符的ASCII码)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include<stdio.h> #include<string.h> int main() { int T; scanf("%d", &T); int i, j; while(T --) { char s[2000]; scanf("%s", s); char c; int len; int a[123] = {0}; len = strlen(s); for(i = 0; i < len - 1; i ++)//给字母排序; for(j = i; j < len; j ++) if(s[i] < s[j]) { c = s[i]; s[i] = s[j]; s[j] = c; } int max = 0, flag; for(i = 97; i < 123; i ++)//分别找26个字母的个数; { for(j = 0; j < len; j ++) { if(i == (s[j] + 0)) { a[i] += 1; } } } for(i = 97; i < 123; i ++)//找26个字母中个数最多的; { if(a[i] > max) { max = a[i]; flag = i;//用flag记录下字母的ASCII码; } } printf("%c\n", flag); } return 0; } |