编程题目:到底买不买

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HaloTrriger/article/details/80905929

题目:链接https://www.nowcoder.com/questionTerminal/2f13c507654b4f878b703cfbb5cdf3a5
来源:牛客网

小红想买些珠子做一串自己喜欢的珠串。卖珠子的摊主有很多串五颜六色的珠串,但是不肯把任何一串拆散了卖。于是小红要你帮忙判断一
下,某串珠子里是否包含了全部自己想要的珠子?如果是,那么告诉她有多少多余的珠子;如果不是,那么告诉她缺了多少珠子。

为方便起见,我们用[0-9]、[a-z]、[A-Z]范围内的字符来表示颜色。例如,YrR8RrY是小红想做的珠串;那么ppRYYGrrYBR2258可以买,因为包含了
全部她想要的珠子,还多了8颗不需要的珠子;ppRYYGrrYB225不能买,因为没有黑色珠子,并且少了一颗红色的珠子。

输入描述

每个输入包含1个测试用例。每个测试用例分别在2行中先后给出摊主的珠串和小红想做的珠串,两串都不超过1000个珠子。

输出描述

如果可以买,则在一行中输出“Yes”以及有多少多余的珠子;如果不可以买,则在一行中输出“No”以及缺了多少珠子。其间以1个空格分隔。

输入

ppRYYGrrYBR2258
YrR8RrY

输出

Yes 8

解题关键

使用哈希表能有效解决此问题,创建两个数组,分别记录摊主的串和小红需要的串。
遍历摊主的串,每个元素ASCII码对应数组下标,找一个元素,就在对应位置值加1。
遍历小红的串,找一个元素,如果该下标值大于0,就让值减1,记录已找到的颜色的count加1。
比对count和小红串的长度,输出对应结果。

C++写法(普通可改成C写法)

using namespace std;
#include <iostream>

int main() {
    int HashTable[128] = { 0 };
    char Source[1000] = { 0 };
    char Aim[1000] = { 0 };
    cin >> Source >> Aim;
    int len1 = strlen(Source);
    int len2 = strlen(Aim);

    for(int i = 0; i < len1; i++)
        ++HashTable[Source[i]];

    int count = 0;
    for (int i = 0; i < len2; i++) {
        if (HashTable[Aim[i]] > 0) {
            --HashTable[Source[i]];
            ++count;
        }
    }
    if (count == len2)
        cout << "Yes" << " " << len1 - count << endl;
    else
        cout << "No" << " " << len2 - count << endl;

    return 0;
}

C++写法(对象)

#include<string>
#include<string.h>
#include<iostream>
using namespace std;

class Garland
{
public:
    string SouGarland;//店主珠串
    string AimGarland;//小红想要的珠串
    int color[128];//颜色数组
    int count;
    Garland()
    {
        memset(color, 0, sizeof(color));
        count = 0;
    }

    void Statistics()//把摊主珠串颜色存放到color数组
    {

        //店主珠串用hashtable存放
        string::iterator it = SouGarland.begin();
        while (it != SouGarland.end())
        {
            ++color[*it];
            ++it;
        }
    }
    void Judege()
    {
        string::iterator it = AimGarland.begin();
        while (it != AimGarland.end())
        {
            if (color[*it] > 0)
            {
                --color[*it];
                ++count;            
            }                   
            ++it;
        }

    }

};


int main()
{
    Garland garland;
    cin >> garland.SouGarland;
    cin >> garland.AimGarland;
    garland.Statistics();//统计
    garland.Judege();
    if (garland.count==garland.AimGarland.size())
    {
        cout<<"Yes "<<garland.SouGarland.size() - garland.count;
    }
    else
    {
        cout<<"No "<<garland.AimGarland.size()-garland.count;
    }
    return 0;
}

个人推荐第一种写法,简单明了。

第二种方法的好处是把方法都包装在一个类内,保证了封装性,用户不需了解实现过程,只需调用各个方法即可。

猜你喜欢

转载自blog.csdn.net/HaloTrriger/article/details/80905929