1092. To Buy or Not to Buy (20)
2017-12-03 本文已影响0人
cheerss
PAT-A1092,题目地址:https://www.patest.cn/contests/pat-a-practise/1092
可以理解为比较字符串不同(无序)的题目,需要首先将两个字符串分别遍历一次,分别记录每个字符串中各个字符的数量,然后分别比较每个字符串数量的多少,对于每个字符(珠子),如果“需要”的比“卖”的多,则missing增加,如果“需要”的比卖的“少”,则extra增加。详见代码
#include <cstdio>
#include <cstring>
void check_char(int* count, char ch){
if(ch >= '0' && ch <= '9'){
count[ch - '0']++;
}
else if(ch >= 'a' && ch <= 'z'){
count[ch - 'a' + 10]++;
}
else if(ch >= 'A' && ch <= 'Z'){
count[ch - 'A' + 10 + 26]++;
}
}
int main(){
char shop[1000]; //卖的珠子
char mine[1000]; //需要的珠子
int shop_count[62] = {0}; //记录卖的珠子中每个颜色的数量,0-9,a-z,A-Z
int mine_count[62] = {0};//记录需要的珠子
scanf("%s %s", shop, mine);
int shop_length = strlen(shop);
int mine_length = strlen(mine);
for(int i = 0; i < shop_length; i++){
check_char(shop_count, shop[i]);
}
for(int i = 0; i < mine_length; i++){
check_char(mine_count, mine[i]);
}
int extra = 0, missing = 0;
for(int i = 0; i < 62; i++){
if(shop_count[i] > mine_count[i]){
extra += shop_count[i] - mine_count[i];
}
else if(shop_count[i] < mine_count[i]){
missing += mine_count[i] - shop_count[i];
}
else{}
}
if(missing == 0){
printf("Yes %d\n", extra);
}
else{
printf("No %d\n", missing);
}
return 0;
}