用字符数组ch来记录magazine每个字母出现频率,用ransomNote的字母减去字符数组ch对应的字符出现频率,如果该字符对应的频率小于0,则不够,无法组成ransomNote!
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
//unordered_map<char,int> umap;
int ch[27];
if(ransomNote.size()>magazine.size()){
return false;
}
for(const auto& c:magazine){
++ch[c-'a'];
}
for(const auto& c:ransomNote){
--ch[c-'a'];
if(ch[c-'a']<0){
return false;
}
}
return true;
}
};