题解 | #字符个数统计#

字符个数统计

http://www.nowcoder.com/practice/eb94f6a5b2ba49c6ac72d40b5ce95f50

方法一、借用STL 使用STL的set直接求解,将所有元素插入到set中,求set的元素个数size()即可 因为set(集合)中的元素不会重复

#include <iostream>
#include <set>
using namespace std;

int main(){
    string str;
    while(cin >> str){
        set<char> s;
        for(int i = 0; i < str.length(); i++)
            s.insert(str[i]);
        cout << s.size() << endl;
    }
    return 0;
}

方法二、参考前人的思路,模仿HASH访问,比较巧妙

#include <iostream>
using namespace std;
int main(){
    string str;
    while(cin >> str){
        int cnt = 0;    //不同的字符数
        int array[128] = {0};
        int len = str.length();
        for(int i = 0; i < len; i++){
            int number = int(str[i]);    //转为数字类型
            if(array[number] == 0){
                array[number] = 1;
                cnt++;
            }
        }
        cout << cnt << endl;
    }
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务