很典型的散列题,对于shop和eva有的珠子(即字符),各开一个128长度的整形散列表计数,将字符作为下标读入。
然后从0~127进行遍历,看每个下标下两个散列表的数量,如果有shop<eva说明不买,但是遍历仍然要继续,因为最后要输出所缺珠子的总数。可以在遍历前设置一个布尔变量isEnough看珠子够不够,设置一个整形变量lessNum计算缺少珠子的数量。
如果最后不买,输出lessNum,如果买,那么商店珠子长度减去伊娃珠子长度即为多出的珠子数量。
AC代码
#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>#include<bits/stdc++.h>using namespace std;const int maxn = 1010;const double eps = 1e-3;int main(){char shopStr[maxn];char evaStr[maxn];scanf("%s",shopStr);scanf("%s",evaStr);int shopLen = strlen(shopStr);int evaLen = strlen(evaStr);int shopTable[128] = {0};int evaTable[128] = {0};for(int i=0;i<shopLen;i++){shopTable[shopStr[i]]++;}for(int i=0;i<evaLen;i++){evaTable[evaStr[i]]++;}bool isEnough = true;int lessNum = 0;for(int i=0;i<128;i++){if(evaTable[i]>shopTable[i]){isEnough = false;lessNum += (evaTable[i]-shopTable[i]);}}if(isEnough)printf("Yes %d\n",shopLen-evaLen);else printf("No %d\n",lessNum);return 0;}