1 条题解
-
0
练61.1 统计字符数
解题思路
26项频次数组统计,再按a到z顺序找最大频次,仅严格超过当前最优才替换。
正确性说明
按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。
易错点
同频取ASCII小的字母。
复杂度
时间O(L),空间O(L)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int cnt[26] = {}; for (char c : s) cnt[c - 'a']++; int ans = 0; for (int i = 1; i < 26; i++) if (cnt[i] > cnt[ans]) ans = i; cout << char('a' + ans) << " " << cnt[ans] << "\n"; return 0; }
- 1