🔴力扣原题:
🟠题目简述:
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
🟡解题思路:
- 利用哈希表记录
magazine
字符串的字符频次; - 然后遍历
ransomNote
字符串,如果有字符没在magazine
中则返回false
; - 如果有,则在哈希表中
-1
; - 遍历哈希表,如果有频次
<0
的,则返回false
,否则则返回true
; - over;
🟢C++代码:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> 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;
}
};