【华为机试】12-字符个数统计

版权声明:转载请注明出处!欢迎大家提出疑问或指正文章中的错误! https://blog.csdn.net/pyuxing/article/details/88861252

1- Description

编写一个函数,计算字符串中含有的不同字符的个数。字符在ACSII码范围内(0~127)。不在范围内的不作统计。

输入描述
输入N个字符,字符在ACSII码范围内。
输出描述
输出范围在(0~127)字符的个数。

示例1
输入:
abc
输出:
3

2- Solution

  • 注意resultvec.erase(resultvec.begin() + j); 的使用
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    string strin;
    while(cin >> strin){
        int count = 0;
        vector<int> resultvec;
        for(int i = 0; i < strin.length(); ++i){
            if(strin[i] >= 0 && strin[i] <= 127){
                resultvec.push_back(strin[i]);
            }
        }
        sort(resultvec.begin(),resultvec.end());
        int countnum = 0;
        for(int i = 0; i < resultvec.size(); ++i){//取出重复元素
            for(int j = i + 1; j < resultvec.size(); ++j){
                if(resultvec[i] == resultvec[j]){
                    resultvec.erase(resultvec.begin() + j);//这里不能写成resultvec.erase( j);==》必须是迭代的输入
                    --j;
                }
            }
        }
        cout << resultvec.size()<<endl;
    }
    return 0;
}
  • 对自动排序且去重的情况可以考虑用set,ascii值在[0,127]时插入集合set中,输出set中的元素个数
#include<iostream>
#include<set>
using namespace std;
int main()
{
    char c;
    set<char> s;
    while(cin>>c){
        if(c>=0 && c<=127){
            s.insert(c);
        }
    }
    cout << s.size() <<endl;
}
#include<iostream>
using namespace std;
int main(){
    char ch;
    int arr[128]={0};
    int count=0;
    while(cin>>ch){
        if(ch>=0 && ch<=127){
            arr[ch]++;
        }
    }
    for(int i=0;i<128;i++){
        if(arr[i]>0)
            count++;
    }
    cout<<count<<endl;
    return 0;
}

欢迎关注公众号:CodeLab

猜你喜欢

转载自blog.csdn.net/pyuxing/article/details/88861252