赎金信
解题思路
- 统计magazine中字符出现的字符,用哈希表保存
- 遍历ransomNote,记录其中出现的字符,出现一次,哈希表删除对应的字符
- 遍历哈希表,如果有的字符出现的次数为负数,则不能拼凑出目标字符
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
bool res = true;
unordered_map<char,int> map;
for(int i = 0;i<magazine.length();i++){
map[magazine[i]]++;
}
for(int i = 0;i<ransomNote.length();i++){
map[ransomNote[i]]--;
}
auto iter = map.begin();
while(iter != map.end()){
if(iter->second < 0){
res = false;
break;
}
++iter;
}
return res;
}
};
优雅的写法
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int> hash;
for(auto a : magazine) hash[a]++;
for(auto b : ransomNote){
if(!hash[b]) return false;
hash[b]--;
}
return true;
}
};