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

农场智能管理系统

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

知识点:哈希表

思路:

  1. 首先,创建一个大小为 26 的整数数组 st,用于记录每个字母在 allocations 中出现的次数。数组中的下标代表字母的 ASCII 码减去字母 ‘A’ 的 ASCII 码,这样可以得到对应字母在数组中的位置。
  2. 遍历字符串 allocations 中的每个字符 x:将字符 x 减去字母 ‘A’ 的 ASCII 码,得到对应字母的数组下标,将对应位置的值加1,表示该字母在 allocations 中出现的次数。
  3. 遍历字符串 requirements 中的每个字符 x:将字符 x 减去字母 ‘A’ 的 ASCII 码,得到对应字母的数组下标,将对应位置的值减1。如果减1后的值小于0,则说明 allocations 中不包含足够的该字母,返回 “NO”。
  4. 如果遍历完成后没有出现 requirements 中某个字母在 allocations 中缺失的情况,则返回 “YES”,表示可以构造出 requirements

编程语言:java

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param requirements string字符串
     * @param allocations string字符串
     * @return string字符串
     */
    public  String can_construct(String requirements, String allocations) {
        int[] st = new int[26];

        for (char x : allocations.toCharArray()) {
            st[x - 'A'] += 1;
        }

        for (char x : requirements.toCharArray()) {
            if (--st[x - 'A'] < 0)
                return "NO";
        }

        return "YES";
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务