这道题对应的知识点是HashTable。HashTable中可以存放数量或者是标记量,这两种值一般情况下是互斥关系,因为标记量只能表示状态,不能表示数量。特殊情况,每种情况只有一种时二者可以互换。
本题的情况是要描述珠子的缺少或多余的数量,所以HashTable中存放的应当是数量。当扫描到的时候,减去1,循环结束后余下的是正数则整体多余,可以买。如果扫描中出现一次负数就不能买,此时要统计会出现负数的次数。
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1005;
int main(){
char selllist[maxn],buylist[maxn],c1,c2;
int len1,len2,number = 0;
int HashTable[128] = {0};
bool Buy = true;
cin >> selllist >> buylist;
len1 = strlen(selllist);
len2 = strlen(buylist);
for(int i = 0;i < len1;i++){
c1 = selllist[i];
HashTable[c1]++;
}
for(int i = 0;i < len2;i++){
c2 = buylist[i];
if(HashTable[c2]) {
HashTable[c2]--;
} else if(HashTable[c2] == 0) {
if(Buy) {
Buy = false;
}
number++;
}
}
if(Buy){
for(int i = 0;i < 128;i++) {
if (HashTable[i])
number += HashTable[i];
}
cout << "Yes " << number;
} else {
cout << "No " << number;
}
return 0;
}