题目描述
编写一个函数,计算字符串中含有的不同字符的个数。字符在 ASCII 码范围内( 0~127 ,包括 0 和 127 ),换行表示结束符,不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次
例如, 对于字符串 abaca 而言,有 a、b、c 三种不同的字符,因此输出 3 。
数据范围: 1 ⩽ n ⩽ 500 1\leqslant n\leqslant 500 1⩽n⩽500
输入描述:
输入一行没有空格的字符串。
输出描述:
输出 输入字符串 中范围在(0~127,包括0和127)字符的种数。
示例1
输入:
abc
输出:
3
示例2
输入:
aaa
输出:
1
思路:
- 可以使用哈希表(unordered_map) 来做一个映射 或者使用哈希表的思想做一个键值映射
复杂度
O(n) (输入字符串的长度)
具体实现
#include <iostream>
using namespace std;
// 键值映射
int main() {
char a[128]={0}; // 键值映射
string str;
int count=0;
cin >> str;
for (int i = 0; i < str.size(); i++){
if(a[str[i]] == 0){
a[str[i]]=1;
count++;
}
}
cout<<count<<endl;
}
/*
哈希表 unordered_map
*/
#include <iostream>
#include<unordered_map>
using namespace std;
int main() {
unordered_map<char,int>a; // 创建哈希表
string str;
int count=0;
cin >> str;
for (int i = 0; i < str.size(); i++){
if(!a.count(str[i])) a[str[i]]++;
}
for(auto it = a.begin(); it != a.end(); it++){
count++;
}
cout<<count<<endl;
}
小结
通过映射来记录不同字符出现的次数 然后遍历记录的辅助表(or 数组) 来查看不同字符的数量