接替方法就是用两个哈希表!
public class num3 {
//该题的思路就是用两个map,存储对应字母和其数量
//如果words单词中对应字母都能在单词表对应的map中找到
//并且words中的个数小于chars中的个数时,就可以。
List<String>solution( )
{
String chars="welldonehoneyr";
String[]words={"hello","world","leetcode"};
Map<Character,Integer>map1=new HashMap<>();
List<String>result=new ArrayList<>();
// String[]result=new String[];
for(int i=0;i<chars.length();i++)
{
map1.put(chars.charAt(i),map1.getOrDefault(chars.charAt(i),0)+1);
}
for(String Words:words)
{
if(Words!=null)
{
if(check(Words,map1))
{
result.add(Words);
}
}
}
return result;
}
boolean check(String word,Map<Character,Integer>map1)
{
Map<Character,Integer>map2=new HashMap<>();
for(int i=0;i<word.length();i++)
{
map2.put(word.charAt(i),map2.getOrDefault(word.charAt(i),0)+1);
}
boolean ans=true;
for(int i=0;i<word.length();i++) {
if ( map1.getOrDefault(word.charAt(i),0)<map2.getOrDefault(word.charAt(i),0)) {
ans = false;
break;//这里一定要 一开始判断为真,后面如果有不满足,就变成false,然后break
}
}
return ans;
}