题解 | #字符个数统计#

字符个数统计

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

两种方法,异曲同工

Way1 哈希表

#include <bits/stdc++.h>
using namespace std;

int countDif(string s) {
    int ans=0;
    int flag[128]={0};
    for(int i = 0; i < s.length(); i++) {
        int a = int(s[i]);
        if(flag[a] == 0) {
            flag[a] = 1;
            ans++;
        }
    }
    return ans;
}

int main() {
    string s;
    getline(cin, s);
    cout << countDif(s);
    return 0;
}

Way2 STL

#include <bits/stdc++.h>
using namespace std;

int countDif(string s) {
    set<char> st;
    for(int i = 0; i < s.length(); i++) {
        st.insert(s[i]);
    }
    return st.size();
}

int main() {
    string s;
    getline(cin, s);
    cout << countDif(s);
    return 0;
}
全部评论
米奇妙妙屋
点赞 回复 分享
发布于 2022-08-09 21:38

相关推荐

05-23 19:02
吉林大学 Java
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

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