Java 题解 | #农场智能管理系统#
农场智能管理系统
https://www.nowcoder.com/practice/a1461ace00224e5a9fc6ff3d1ae587e5
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param requirements string字符串
* @param allocations string字符串
* @return string字符串
*/
public String can_construct (String requirements, String allocations) {
// write code here
if (requirements.length() > allocations.length()) {
return "NO";
}
Map<Character, Integer> allocationCounts = new HashMap<>();
for (char c : allocations.toCharArray()) {
allocationCounts.put(c, allocationCounts.getOrDefault(c, 0) + 1);
}
for (char c : requirements.toCharArray()) {
if (!allocationCounts.containsKey(c) || allocationCounts.get(c) == 0) {
return "NO";
}
allocationCounts.put(c, allocationCounts.get(c) - 1);
}
return "YES";
}
}
java代码
该题考察的知识点是字符串处理和哈希表的应用。
使用哈希表来统计allocations中每个字符的出现次数,并根据requirements来检查是否能够满足要求。
检查requirements的长度是否大于allocations的长度,如果是,则说明无法使用allocations中的字符构成requirements,直接返回"NO"。
初始化一个空的哈希表allocationCounts来记录allocations中每个字符的出现次数。
遍历allocations中的每个字符,并将其添加到allocationCounts中。如果字符已经存在于哈希表中,增加对应字符的出现次数;否则,将该字符添加到哈希表并设置出现次数为1。
然后,遍历requirements中的每个字符,对于每个字符,进行以下操作:
- 如果字符c不在allocationCounts中,或者字符c在allocationCounts中的出现次数已经为0,说明无法满足要求,返回"NO"。
- 否则,我们从allocationCounts中减少字符
c的出现次数。
最后,如果以上步骤都通过了,说明可以使用allocations中的字符构成requirements,返回"YES"。
最终返回值是一个字符串,表示是否可以使用allocations中的字符构成requirements。
该算法的时间复杂度为O(m+n),m和n为allocations和requirements的长度。

百度公司氛围 562人发布