【PAT_1062】To Buy or Not to Buy
問題描述
eva想用她最喜歡的顏色做一串珠子,她去了一家小店買了一些珠子。 有許多五顏六色的珠子串。 然而,商店只會將整個珠子串出售。 因此,伊娃必須檢查商店中的字串是否包含她需要的所有珠子。 她現在來找你幫忙:如果答案是“是”,請告訴她額外的數量必須買的珠子; 或者如果答案是“否”,請告訴她字串中缺少的珠子數量。 為簡單起見,讓我們使用範圍中的字元
[0-9],[a-z]和[A-Z]代表顏色。
輸入:
第一行:商店的珠子串的顏色序列whole
第二行:eva所需要的珠子的顏色序列needs
輸出:
如果答案是“是”,那麼還輸出Eva必須購買的額外珠子的數量;
即Yes 額外珠子數量
如果答案為“否”,則還輸出字串中缺少的珠子數less。
即No 缺少的珠子數。
答案和號碼之間必須有1個空格。
解題思路:
將商店的序列和需要的序列分佈都存在一個map中,得出每個序列中<顏色(key),顏色數(val)>
對於need_map中的每一種顏色key,判斷whole_map中的key的val是否小於於need_map中的val,小於則答案為否,less += whole_val-need_val;
遍歷完之後如果less>=0,則能滿足條件,額外多買的珠子為whole.size()-need.size();
程式碼
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
int main() {
string whole, needs;
cin >> whole>> needs;
map<char, int> dic;
map<char, int> whole_dic;
int less = 0;
for (int i = 0; i < needs.size(); i++) {//需要的序列存入map中
if (dic.find(needs[i]) != dic.end()) {
dic[needs[i]]= dic[needs[i]] +1;
}
else {
dic.insert(pair<int, int>(needs[i], 1));
}
}
for (int i = 0; i < whole.size(); i++) {//售出的序列存入map
if (whole_dic.find(whole[i]) != whole_dic.end()) {
whole_dic[whole[i]] = whole_dic[whole[i]] + 1;
}
else {
whole_dic.insert(pair<int, int>(whole[i], 1));
}
}
map<char, int>::iterator it;
it = dic.begin();
while (it != dic.end())
{
if (whole_dic.find(it->first) == whole_dic.end()) {//判斷商店售賣的某種顏色是否能滿足需要的值
less += it->second;
}
else {
if (whole_dic[it->first] < it->second) {
less += it->second - whole_dic[it->first];
}
}
it++;
}
if (less != 0) {
cout << "No " << less << endl;
}
else {
cout << "Yes " << (whole.size()-needs.size()) << endl;
}
return 0;
}
相關文章
- 121|Best Time to Buy and Sell Stock
- [leetcode]Best Time to Buy and Sell StockLeetCode
- Best Time to Buy and Sell Stock系列
- 題解:P10688 Buy Tickets
- [LeetCode] 2073. Time Needed to Buy TicketsLeetCode
- 121. Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock系列分析
- 貪心法-Best Time to Buy and Sell Stock
- [LeetCode] 121. Best Time to Buy and Sell StockLeetCode
- How to Buy a Fake Cal Poly Pomona Diploma Quickly?UI
- leetcode_best-time-to-buy-and-sell-stock-iiLeetCode
- [LeetCode] 122. Best Time to Buy and Sell Stock IILeetCode
- leetcode best-time-to-buy-and-sell-stock-iii(Java)LeetCodeJava
- 【Lintcode】393. Best Time to Buy and Sell Stock IV
- LeetCode 309. Best Time to Buy and Sell Stock with CooldownLeetCode
- DedeCMS最新通殺注入(buy_action.php)漏洞分析PHP
- Goal2: buy 85 mining, I now have 74 mining and I believeGo
- 【leetcode】40-best-time-to-buy-and-sell-stock 力扣 121. 買賣股票的最佳時機LeetCode力扣
- 42-best-time-to-buy-and-sell-stock-iii 力扣 123. 買賣股票的最佳時機 III力扣
- Buy Shares:2020上半年美國電動車銷量中特斯拉佔比超過80%
- 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 最佳買賣股票時機含冷凍期(Medium)(JAVA)LeetCodeJava
- 44-best-time-to-buy-and-sell-stock-with-cooldown 力扣 309. 買賣股票的最佳時機包含冷凍期力扣
- TTEC遭勒索軟體攻擊後影響客戶業務 包括Verizon、Best Buy、美國銀行等