1042 字符统计 (20 分)(算法分析+代码实现)

76 阅读1分钟

1042 字符统计 (20 分)

题目链接

算法分析

依次读入字符串的每个字母,对于两种情况进行处理
1.大写字母:把它ASCII加上32得到对应的小写字母。
2.小写字母:统计其出现的次数,并进行最大出现次数和字母序的判断。

代码实现

#include<bits/stdc++.h>
using namespace std;
#define N 300
int cnt[N];//用一个栈存下某一字母出现的次数
int main(){
	int mx = -1;
	char s, ans = 'z';
	while((s = getchar()) != '\n'){
		if(isupper(s))//ascii A-65 a-97
			s += 32;
		if(islower(s)){
			int m = (++ cnt[(int)s]);
			if(m > mx){
				mx = cnt[(int)s];
				ans = s;
			}
			else if(m == mx)
				ans = min(ans, s);
		}
	}
	printf("%c %d", ans, mx);
	return 0;
}