如果注释中包含的所有单词都出现在杂志上(大小写敏感),程序应该打印“是”,否则打印“否”。杂志中的每个词只能使用一次,也就是说,如果注释中有两个相同的单词,那么该杂志还必须至少包含该词两次。
#include<iostream>
#include<vector>
#include<string>
#include<unordered_map>
using namespace std;
void checkMagazine(vector<string> magazine, vector<string> note) {
// Inserts magazine vector into an unordered_map for quick access
unordered_map<string, int> umap;
for (auto& x : magazine)
umap[x] = 1;
// For each word in note search the unordered_map for that word
for (auto& word : note) {
if (umap.find(word) == umap.end()) { // Word not in magazine
cout << "No" << endl;
return;
}
else // Remove single instance of that word
umap.erase(word);
}
cout << "Yes" << endl;
return;
}
int main()
{
vector<string> magazine = { "Help", "me", "please", "please" };
vector<string> note = { "Help", "please", "please" };
checkMagazine(magazine, note);
return 0;
}or条件需要从umap中删除该单个节点(或仅删除该特定单词的单个实例),但据我所知,唯一能够做到这一点的修饰符是“提取”,但,我不能使用C++17。
有什么方法可以解决这个问题,还是这种类型的方法不适用于unordered_map?是否更适合列出一个链接的清单?我是新的数据结构,所以任何帮助都将不胜感激。
发布于 2020-01-28 22:31:16
这种性质的东西。我写它时没有太多的思考,也没有经过检查,所以带着一点点盐(也许是对的)。这样做的目的是使用一个单词出现在杂志上的次数,并在你在笔记中找到它时减去它。
unordered_map<string, int> mp;
for(const auto& s: magazine) mp[s]++;
for(const auto& s: note) {
auto it = mp.find(s);
if(it == mp.end() || it->second <= 0) { cout << "No"; return; }
it->second--; // if(!--it->second) mp.erase(it);
if(!it->second) mp.erase(it);
}
cout << "Yes";https://stackoverflow.com/questions/59957796
复制相似问题