- 力扣原题:
- 题目简述:
- 解题思路:
- C++代码:
- 结果展示:
力扣原题:
383. 赎金信
题目简述:给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
解题思路:- 利用哈希表记录magazine字符串的字符频次;
- 然后遍历ransomNote字符串,如果有字符没在magazine中则返回false;
- 如果有,则在哈希表中-1;
- 遍历哈希表,如果有频次<0的,则返回false,否则则返回true;
- over;
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map umap;
for(auto ch : magazine)
{
++umap[ch];
}
for(auto ch : ransomNote)
{
if(umap.count(ch) == 1)
{
--umap[ch];
}
else
{
return false;
}
}
for(auto it = umap.begin(); it != umap.end(); it++)
{
if(it->second < 0)
{
return false;
}
}
return true;
}
};
结果展示:



