题解 | #农场智能管理系统#
农场智能管理系统
https://www.nowcoder.com/practice/a1461ace00224e5a9fc6ff3d1ae587e5
- 题目考察的知识点 : 字符串,哈希
- 题目解答方法的文字分析:
- 先遍历 allocations 字符串,将其中每个字符出现的次数保存在一个哈希表 mapping 中。然后遍历 requirements 字符串,检查其中每个字符是否都在 mapping 中出现过,并且当前字符还没有超过其在 mapping 中出现的次数。
- 可以使用 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题的解法思路
安克创新 Anker公司福利 814人发布

