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

农场智能管理系统

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 (allocations.length() < requirements.length()) {
            return "NO";
        }
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < requirements.length(); i++) {
            map.put(requirements.charAt(i), map.getOrDefault(requirements.charAt(i),
                    0) + 1);
        }
        int count = requirements.length();
        for (int i = 0; i < allocations.length(); i++) {
            if (map.containsKey(allocations.charAt(i))) {
                if (map.get(allocations.charAt(i)) > 0) {
                    count--;
                }
                map.put(allocations.charAt(i), map.get(allocations.charAt(i)) - 1);
            }
            if (count == 0) {
                return "YES";
            }
        }
        return "NO";
    }

}

本题考察的知识点是如何判断一个字符串能否由另一个字符串的所有字符构成,所用编程语言是java。

我可以用一个哈希表统计字符串requirements各个字符的频率,用计数器count来记录字符串requirement需要匹配的字符数。遍历allocations的各个字符,如果哈希表中存在相应字符,如果对应的频率数大于0,则count减一,只要存在相应字符则需要更新相应哈希表中字符对应的频数。如果count等于0,则能够构成,否则不能构成

全部评论

相关推荐

10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
牛客吹哨人:哨哥晚点统一更新到黑名单:能救一个是一个!26届毁意向毁约裁员黑名单https://www.nowcoder.com/discuss/1525833
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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