牛客网--统计字符

来源:互联网 发布:软件开发公司上市资质 编辑:程序博客网 时间:2024/06/05 10:15

题目描述

给定一个英文字符串,请写一段代码找出这个字符串中首先出现三次的那个英文字符。

输入描述:

输入数据一个字符串,包括字母,数字等。

输出描述:

输出首先出现三次的那个英文字符
思路: C++
题目说的是给定英文字符串,而要统计的是字母,注意是字母,这是个坑。用关联容器map,将读入的字符依次计数,当字符首次出现的字数为三时,输出这个字符,并终止程序。
#include <iostream>#include <map>#include <cctype>using namespace std;int main(){    char ch;    map<char, size_t> ch_count;        while (cin >> ch){        if (isalpha(ch)){ //当字符时字母时            ++ch_count[ch];            if (ch_count[ch] == 3){ //ch_count[ch]等价于,从一个map对象中取出的pair类型对象的second数据成员                cout << ch << endl;                return 0;            }        }    }    return 0;}

C:
#include <stdio.h>#include <ctype.h>int main(void){    int ch;    int count[256] = {0}; //能够出现的字符一共右256个,所以数组的容量为256,并全部初始化为0        while ((ch = getchar()) != EOF){        if (isalpha(ch)){            ++count[ch]; //字符能够转化为某个整数,且在0~255之间,以其作为下标,并递增下标坐在的值            if (count[ch] == 3){                putchar(ch);                return 0;            }        }    }    return 0;}

原创粉丝点击