题目
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
题目解析
勒索信
罪犯写勒索信时为了不暴露字迹,要从杂志上搜索所有需要的字母,组成单词来表达的意思。所以要求杂志上的字母要能满足勒索信上的所有字母需求,且不计顺序。
答案
public boolean canConstruct(String ransomNote, String magazine) {
int[] nums = new int[26];
for (int i = 0; i < magazine.length(); i++) {
nums[magazine.charAt(i) - 'a']++;
}
for (int j = 0; j < ransomNote.length(); j++) {
if (--nums[ransomNote.charAt(j) - 'a'] < 0) return false;
}
return true;
}