题解 | #农场智能管理系统#

农场智能管理系统

https://www.nowcoder.com/practice/a1461ace00224e5a9fc6ff3d1ae587e5

考察的知识点:字符串;

解答方法分析:

  1. 创建一个无序映射(unordered_map)count,用于记录每个字符在分配字符串中出现的次数。
  2. 遍历分配字符串 allocations 中的每个字符 ch,并将其在 count 中对应的计数增加。
  3. 遍历需求字符串 requirements 中的每个字符 ch:如果该字符 ch 在 count 中不存在(即未在分配字符串中出现),或者 count[ch] 的计数已经为 0,则返回 "NO",表示无法满足需求。否则,将 count[ch] 的计数减一,表示已经使用了一个该字符来满足需求。
  4. 在遍历完需求字符串后,再次遍历 count 中的每个键值对 it:如果某个字符的计数 it.second 大于 0,则表示还有剩余的该字符没有被使用,即无法满足全部需求,返回 "YES"。
  5. 如果以上步骤都没有返回结果,则表示可以满足全部需求,返回 "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";
    }
    
};

全部评论

相关推荐

程序员小白条:这比例牛逼,750:1
点赞 评论 收藏
分享
绝迹的星:前端和后端写两份简历, 如果想干全栈就直接写求职意向为全栈工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务