现在的位置: 首页 > 综合 > 正文

baidu c++吧上的一道题

2013年03月04日 ⁄ 综合 ⁄ 共 1377字 ⁄ 字号 评论关闭

题目在:http://post.baidu.com/f?kz=70481398
统计字母个数:
程序输入一个字符串(长度不超过100),全是小写字母.
统计小写字母出现的次数,并用要求的图表示出来.
测试数据:

Input:
sadjhasdhqwpopeepomcxnnbladkjkfjasjas

Output:
@
@                 @                 @
@     @           @           @     @
@     @ @     @   @ @     @ @ @     @
@ @ @ @ @ @   @   @ @ @ @ @ @ @ @   @       @ @
a b c d e f g h i j k l m n o p q r s t u v w x y z
 
注意:
在字符串中每个小写字母的个数不会超过20个.
编程语言:C/C++.

_________________________________________________
题目意思就是每个字母有多少个,上面就输出多少@。我用一个长度为26的数组(数组int count[26])来保存每个字母的个数,然后用一个26*20(因为说了每个字母个数都不超过20个)的数组(数组chars)来记录最后输出的结果,这个数组中的刚开始初始化为空字符,每次碰到一个字母就将其赋值为@,最后只要把这个数组从最高的一排向下输出就得到结果了,但是上面好多排都可能是空字符,要从第一排含有至少一个非空字符(即@)的向下输出,所以我用了一个变量(int max_count)来记录这一排的位置。程序如下:

#i nclude <iostream> 
using namespace std;

#define COUNT 20

void output(char *p)
{

    char chars[26][COUNT];
    for(int i=0;i<26;i++)
        for(int j=0;j<COUNT;j++)
            chars[i][j]
=' ';

    int count[26];
    for(int i=0;i<26;i++)
        count[i]
=0;

    int max_count=0;
    int index=0;
    int tmp=0;
    while(*p!='\0')
    {
        index
=*p-'a';
        tmp
=++count[index];
        if(max_count<tmp)
            max_count
=tmp;
        chars[index][tmp
-1]='@';
        p
++;
    }

    for(int i=max_count-1;i>=0;i--)
    {

        for(int j=0;j<26;j++)
            cout
<<chars[j][i];
        cout
<<endl;
    }

    for(char i='a';i<='z';i++)
        cout
<<i;
}

int main()
{

    char *str="sadjhasdhqwpopeepomcxnnbladkjkfjasjas",*p=str;
    output(p);
    getchar();

    return 0;
}

 

【上篇】
【下篇】

抱歉!评论已关闭.