知识点
字符串,哈希
解题思路
这道题的意思是能否用allocations中的字符构成requirements,字符不能重复使用。
使用两个map来分别存放两个字符串字符对应的数量,比较这两个map,如果allocations对应的字符的数量少于了requirements对应字符的数量,表示可提供的字符少于需要的字符数返回false,遍历完map就可以返回true。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param requirements string字符串
* @param allocations string字符串
* @return string字符串
*/
public String can_construct (String requirements, String allocations) {
HashMap<Character,Integer> map1=new HashMap<>();
for(int i=0;i<requirements.length();i++){
char ch=requirements.charAt(i);
map1.put(ch,map1.getOrDefault(ch,0)+1);
}
HashMap<Character,Integer> map2=new HashMap<>();
for(int i=0;i<allocations.length();i++){
char ch=allocations.charAt(i);
map2.put(ch,map2.getOrDefault(ch,0)+1);
}
for(char ch:map1.keySet()){
if(map2.get(ch)==null||map2.get(ch)<map1.get(ch)){
return "NO";
}
}
return "YES";
}
}



京公网安备 11010502036488号