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,则能够构成,否则不能构成