LeetCode 383. Ransom Note

简介: 给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。

v2-200b553dad3c206dc98b0c4cb4ab13a2_1440w.jpg

Description



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


描述



给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。


(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)


注意:


你可以假设两个字符串均只含有小写字母。

canConstruct("a", "b") -> false

canConstruct("aa", "ab") -> false

canConstruct("aa", "aab") -> true


来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/ransom-note

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路


  • ransomNote 中出现的字符必须都出现在 magazine 中。
  • 使用字典,健为字符,值为字符出现的次数,用 ransomNote 对应的字典减去 magazine 对应的字典,如果结果为空,说明 ransomNote 中的字符全部在 magazine 中出现过。


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-07-30 07:58:59
# @Last Modified by:   何睿
# @Last Modified time: 2019-07-30 08:03:10
from collections import Counter
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        return not (Counter(ransomNote) - Counter(magazine))

源代码文件在 这里


目录
相关文章
LeetCode之Ransom Note
LeetCode之Ransom Note
92 0
[LeetCode]--383. 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
1308 0
|
Java
[LeetCode] Ransom Note
A very typical application of hash maps. Since I am now learning Java, I code in Java. The following code uses toCharArray() and getOrDefault(), which are learnt from this post.
894 0
|
1天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
1天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0
|
1天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
25 4
【刷题】 leetcode 面试题 08.05.递归乘法