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

农场智能管理系统

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

  • 题目考察的知识点 : 字符串,哈希
  • 题目解答方法的文字分析:
  1. 先遍历 allocations 字符串,将其中每个字符出现的次数保存在一个哈希表 mapping 中。然后遍历 requirements 字符串,检查其中每个字符是否都在 mapping 中出现过,并且当前字符还没有超过其在 mapping 中出现的次数。
  2. 可以使用 Counter 函数来统计 allocations 字符串中每个字符的出现次数。然后,我们遍历 requirements 字符串,在遍历过程中对 mapping 进行更新。如果当前字符已经在 mapping 中出现过,则检查其出现次数是否还未达到其在 allocations 中出现的次数;否则,说明当前字符不在 allocations 中,直接返回 "NO"。当遍历结束后,如果 requirements 中所有字符都满足条件,则返回 "YES";否则,返回 "NO"。
  • 本题解析所用的编程语言: Python
  • 完整且正确的编程代码

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param requirements string字符串
# @param allocations string字符串
# @return string字符串
#
from collections import Counter


class Solution:
    def can_construct(self, requirements: str, allocations: str) -> str:
        counts = Counter(allocations)
        mapping = {}

        for r in requirements:
            if r not in counts:
                return "NO"
            if r in mapping:
                if mapping[r] == counts[r]:
                    return "NO"
                else:
                    mapping[r] += 1
            else:
                mapping[r] = 1

        return "YES"
牛客高频top202题解系列 文章被收录于专栏

记录刷牛客高频202题的解法思路

全部评论

相关推荐

06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
07-07 17:06
已编辑
深圳技术大学 golang
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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