-
题目:
PAT地址 -
题目大意:
给出一个string1,里面每个字符代表一个颜色。再给出一个string2,里面每个字符也代表一个颜色。要求检查string1里是否有能构成string2的所有字符,若有,输出"Yes" + string1多余字符的个数,若没有,输出"No" + string1不足的字符的个数。
-
思路一:
- 分别用两个map存两个字符串,键值对形式为:(color, 出现的次数)
- 看map2中每个颜色是否在map1中存在,且map1中颜色的次数是否依次 小于等于 map2中的对应色的次数
- 如果是,则用map1的总数-map2的总数;如果不是,用map2的总数-map1中存在的对应颜色的总数(若map1中不存在该颜色,则value=0)
-
代码:
#include <iostream> #include <string> #include <map> using namespace std; int main() { string s1, s2; cin >> s1 >> s2; map<char, int> map1; map<char, int> map2; for(int i = 0; i < s1.length(); i++){ map1[s1[i]]++; } for(int i = 0; i < s2.length(); i++){ map2[s2[i]]++; } string flag = "Yes"; for(auto i = map2.begin(); i != map2.end(); i++){ //包含两种情况:map1中无该颜色、map1中该颜色的次数比map2中的小。 if(map1[i -> first] < i -> second) { flag = "No"; break; } } int sum = 0; if(flag == "Yes"){ // Yes int sum1 = 0; for(auto i = map1.begin(); i != map1.end(); i++){ sum1 += i -> second; } int sum2 = 0; for(auto i = map2.begin(); i != map2.end(); i++){ sum2 += i -> second; } sum = sum1 - sum2; } else{ // No for(auto i = map2.begin(); i != map2.end(); i++){ if(map1[i -> first] >= i -> second) continue; else sum += i ->second - map1[i -> first]; } } printf("%s %d", flag.c_str() , sum); return 0; }
-
思路二
- 先用一个数组v存储商店提供的bead,下标为颜色,value为颜色出现的次数, 记录存入珠子的个数;
- 输入目标bead,每个字符代表一个颜色。每输入一个color,就检查v[color];
- 若v[color] > 0, 则flag = ture, v[color]–;若v[color] <= 0, 则flag = false, count++, continue;
- 判断flag,若为true,表示买得到所需的珠子,计算v的总和,就是多出来的个数;若为false,表示有的珠子买不到,count数就是所缺的珠子个数。
-
代码
#include <iostream> using namespace std; int v[256]; // 尽量设置得大点 int main() { char color; int p = 0, count1 = 0, count2 = 0; bool flag = true; while(scanf("%c", &color) && color != '\n'){ // 遇'\n'停止 count1++; // 记录珠子个数 v[color]++; } while(scanf("%c", &color) && color != '\n'){ if(v[color] > 0){ count1--; // 记录珠子个数 v[color]--; } else{ count2++; flag = false; } } if(flag == true) printf("Yes %d", count1); else printf("No %d", count2); return 0; }
-
总结:
-
思路一没用到hash,思路二用到了hash;
-
设置存储hash的数组可以尽量设大一点;
-
c++中map可随意访问、插入任意index,vector不行;
-
ASCII码:共有128个
- 10 = ’\n‘
- 48~57: 0 ~ 9
- 65 ~ 90: ’A‘ ~ ’Z‘
- 97 ~ 122: ‘a’ ~ ‘z’
-
我写代码思路不够严谨,经常会写着写着断开了。比如我在想计算商店beads缺少珠子的个数,突然卡壳了。
-
【PAT】1092 To Buy or Not to Buy (20 分)
最新推荐文章于 2021-10-11 19:59:30 发布