Subject: 383. Ransom Letter
Since this question only contains lowercase letters, and the letters in the magazine cannot be reused.
Therefore, first use an integer array with a length of 26 to record the number of occurrences of letters in the magazine.
Then use this integer array to traverse and compare with ransomeNote. When -1 appears in the array, it means false, otherwise true.
code:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] tmp = new int[26];
//遍历magazine中的字符
for(int i=0;i<magazine.length();i++){
char ch = magazine.charAt(i);
tmp[ch-'a']++;
}
//遍历ransomNote中的字符
for(int i=0;i<ransomNote.length();i++){
char ch = ransomNote.charAt(i);
tmp[ch-'a']--;
if(tmp[ch-'a']<0){
return false;
}
}
return true;
}
}