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
思路:用伪哈希表来扫两次,第一次扫magazine,相应位++,第二次扫ransomNote,相应位–,最后遍历一遍哈希表,如果存在负数,则返回false,否则返回true。
public boolean canConstruct(String ransomNote, String magazine) {
//special case
if (ransomNote.length() == 0) return true;
if (magazine.length() == 0) return false;
if (ransomNote.length() > magazine.length()) return false;
//general case
int[] set = new int[256];
for (int i = 0; i < magazine.length(); i++) {
char r = magazine.charAt(i);
set[r]++;
}
for (int i = 0; i < ransomNote.length(); i++) {
char r = ransomNote.charAt(i);
set[r]--;
}
for (int i : set) {
if (i < 0) return false;
}
return true;
}