写一个算法实现统计在输入字符串中各个不同字符出现的频度。(字符串中的合法字符A~Z这26个字母和0~9这10个数字)。
时间: 2024-05-01 16:23:41 浏览: 20
可以使用一个长度为36的数组来记录每个字符出现的频率,数组下标0~25分别对应A~Z这26个字母,下标26~35分别对应0~9这10个数字。具体实现如下:
```python
def count_chars(s):
freq = [0] * 36 # 初始化频率数组
for c in s:
if c.isalpha(): # 如果是字母
freq[ord(c.upper()) - ord('A')] += 1 # 将字母转换为大写后减去A的ASCII码,作为下标
elif c.isdigit(): # 如果是数字
freq[ord(c) - ord('0') + 26] += 1 # 将数字减去0的ASCII码,作为下标
return freq
```
这个算法的时间复杂度为$O(n)$,其中$n$是输入字符串的长度。
相关问题
写一个算法,统计在输入字符串中各个不同字符出现的频度,字符串中的合法字符为a~z和0~9。
可以用一个长度为 36 的数组来存储每个字符出现的次数,数组下标对应着字符的 ASCII 码,具体实现如下:
```python
def count_chars_frequency(s):
freq = [0] * 36 # 初始化数组,下标0~25表示a~z,下标26~35表示0~9
for c in s:
if c.isalpha(): # 如果是字母,先把 ASCII 码转换为下标
index = ord(c.lower()) - ord('a')
elif c.isdigit(): # 如果是数字,先把 ASCII 码转换为下标
index = ord(c) - ord('0') + 26
else: # 如果是非法字符,直接跳过
continue
freq[index] += 1 # 对应字符出现次数加一
return freq
```
该算法的时间复杂度为 $O(n)$,其中 $n$ 是输入字符串的长度。
采用C++写一个算法,统计在输入字符串中各个不同字符出现的频度,字符串中的合法字符为a~z和0~9
以下是采用 C++ 编写的算法,实现统计输入字符串中各个不同字符出现的频度:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 36; // 字符种类数
int cnt[MAXN]; // 记录每种字符出现的次数
int main()
{
char str[1000];
cin >> str;
int len = strlen(str);
for (int i = 0; i < len; i++)
{
if (isdigit(str[i])) // 判断是否为数字
{
cnt[str[i] - '0']++;
}
else if (isalpha(str[i])) // 判断是否为字母
{
if (isupper(str[i])) // 大写字母转为小写字母
str[i] = tolower(str[i]);
cnt[str[i] - 'a' + 10]++;
}
}
for (int i = 0; i < 10; i++) // 输出数字的频度
{
cout << i << " " << cnt[i] << endl;
}
for (int i = 0; i < 26; i++) // 输出字母的频度
{
cout << char('a' + i) << " " << cnt[i + 10] << endl;
}
return 0;
}
```
该算法的基本思路是:遍历输入字符串,判断字符是否为数字或字母,并统计每个字符出现的次数。最后,输出数字和字母的频度。其中,数字的频度存储在数组 cnt 的前 10 个元素中,字母的频度存储在数组 cnt 的后 26 个元素中。如果输入字符串中有大写字母,需要将其转换为小写字母,然后再统计出现次数。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)