题解 | #农场智能管理系统#
农场智能管理系统
https://www.nowcoder.com/practice/a1461ace00224e5a9fc6ff3d1ae587e5
考察的知识点:字符串;
解答方法分析:
- 创建一个无序映射(unordered_map)count,用于记录每个字符在分配字符串中出现的次数。
- 遍历分配字符串 allocations 中的每个字符 ch,并将其在 count 中对应的计数增加。
- 遍历需求字符串 requirements 中的每个字符 ch:如果该字符 ch 在 count 中不存在(即未在分配字符串中出现),或者 count[ch] 的计数已经为 0,则返回 "NO",表示无法满足需求。否则,将 count[ch] 的计数减一,表示已经使用了一个该字符来满足需求。
- 在遍历完需求字符串后,再次遍历 count 中的每个键值对 it:如果某个字符的计数 it.second 大于 0,则表示还有剩余的该字符没有被使用,即无法满足全部需求,返回 "YES"。
- 如果以上步骤都没有返回结果,则表示可以满足全部需求,返回 "Yes"。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: string can_construct(string requirements, string allocations) { unordered_map<char, int> count; for (char ch : allocations) { count[ch]++; } for (char ch : requirements) { if (count.find(ch) == count.end() || count[ch] == 0) { return "NO"; } count[ch]--; } for (auto it : count) { if (it.second > 0) { return "YES"; } } return "Yes"; } };