这个题和之前做过的有效字母异位词非常像,可以说就是变体。
我一开始的思路是用的java内置的hash表,结果发现时间好像比较慢,就考虑到使用数组,自己造hash
//使用HashMap
HashMap<Character,Integer> hashmap =new HashMap<>();
for(int i=0;i<magazine.length();i++){
Character temp=magazine.charAt(i);
if(hashmap.get(temp)==null)
hashmap.put(temp,1);
else hashmap.put(temp,hashmap.get(temp)+1);
}
for(int i=0;i<ransomNote.length();i++){
Character temp=ransomNote.charAt(i);
if(!hashmap.containsKey(temp))
return false;
int num=hashmap.get(temp);
if(num>0)
hashmap.put(temp,num-1);
else return false;
}
return true;
}
//使用数组hash
public boolean canConstruct(String ransomNote, String magazine) {
int[] a=new int[26];
for(int i=0;i<magazine.length();i++){
char t=magazine.charAt(i);
a[t-'a']++;
}
for(int i=0;i<ransomNote.length();i++){
char t=ransomNote.charAt(i);
int num=t-'a';
if(a[num]>0)
a[num]--;
else return false;
}
return true;
}