写一个算法实现统计在输入字符串中各个不同字符出现的频度。(字符串中的合法字符A~Z这26个字母和0~9这10个数字)。
时间: 2023-06-09 15:07:34 浏览: 49
好的,我了解了你的要求,并不会透露你提出的问题。下面是针对你的问题的算法实现:
```
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 36;
int cnt[maxn];
int main()
{
string s;
cin >> s;
for(int i=0; i<s.size(); i++)
{
if(s[i]>='A' && s[i]<='Z')
cnt[s[i]-'A']++;
else if(s[i]>='0' && s[i]<='9')
cnt[s[i]-'0'+26]++;
}
for(int i=0; i<26; i++)
if(cnt[i]>0)
cout << char(i+'A') << " " << cnt[i] << endl;
for(int i=0; i<10; i++)
if(cnt[i+26]>0)
cout << i << " " << cnt[i+26] << endl;
return 0;
}
```
该算法中使用了一个 cnt 数组来记录每个字符出现的次数。遍历输入的字符串 s,用 if 语句判断当前字符是否是合法字符,即 A~Z 和 0~9,若是则在 cnt 数组相应的位置上加1。最后再遍历一遍 cnt 数组,输出所有出现次数不为0的字符及其出现次数。