[LeetCode] Ransom Note 赎金条

简介:


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

非常简单的一道题,就是用哈希表统计字符的个数,参见代码如下:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> m;
        for (char c : magazine) ++m[c];
        for (char c : ransomNote) {
            if (--m[c] < 0) return false;
        }
        return true;
    }
};

本文转自博客园Grandyang的博客,原文链接:赎金条[LeetCode] Ransom Note ,如需转载请自行联系原博主。

相关文章
|
2月前
|
Java
383. 赎金信 --力扣 --JAVA
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能c里面的字符构成。 如果可以,返回 true ;否则返回 false 。 magazine 中的每个字符只能在 ransomNote 中使用一次。
29 1
|
9月前
|
索引
【Leetcode -383.赎金信 -387.字符串中的第一个唯一字符】
【Leetcode -383.赎金信 -387.字符串中的第一个唯一字符】
29 0
|
5天前
|
存储
力扣经典150题第三十九题:赎金信
力扣经典150题第三十九题:赎金信
4 0
|
2月前
|
存储 算法 Java
[Java·算法·简单] LeetCode 383. 赎金信 详细解读
[Java·算法·简单] LeetCode 383. 赎金信 详细解读
32 0
|
2月前
|
算法
六六力扣刷题哈希表之赎金信
六六力扣刷题哈希表之赎金信
23 0
|
8月前
|
算法
代码随想录算法训练营第七天 | LeetCode 454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
代码随想录算法训练营第七天 | LeetCode 454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
31 0
|
算法 Java
【leetcode速通java版】06——赎金信、三数之和
【leetcode速通java版】06——赎金信、三数之和
|
算法 索引
LeetCode每日1题--赎金信
LeetCode每日1题--赎金信
50 0
代码随想录刷题|LeetCode 454.四数相加II 383. 赎金信 15. 三数之和 18. 四数之和
代码随想录刷题|LeetCode 454.四数相加II 383. 赎金信 15. 三数之和 18. 四数之和
代码随想录刷题|LeetCode 454.四数相加II 383. 赎金信 15. 三数之和 18. 四数之和