题目描述:
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
中文理解:给出两个字符串ransomNote和magazine,判断magazine中的字符是否可以构成ransomNote,即ransomNote中出现的字符是否在magazine都出现过,且magazine中出现次数大于等于ransomNote。
解题思路:使用hash的思路,设置一个count[26]的数组,在计数magazine中字符出现次数++,在计数ransomNote出现次数是--,若count存在任何一个元素小于0,返回false,否则返回true。
代码(java):
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int []count=new int[26];
for(char ch:ransomNote.toCharArray()){
count[ch-'a']--;
}
for(char ch:magazine.toCharArray()){
count[ch-'a']++;
}
for(int val:count){
if(val<0)return false;
}
return true;
}
}