[LeetCode][Python]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 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

思路:

  1. 第一反应是依次遍历ransomNote,如果其中的元素都在magazine,则返回True,否则返回False,这个应该可以解决这个问题,不过效率肯定不高。由于元素只能用一次,还要考虑删除的问题。
  2. 使用pop和remove同时处理两个列表,对第一个使用pop(),如果在magazine,则删除之。如果元素不在,则返回False,如果在里面,继续删除。
  3. 使用collections.Counter(),对于两个Counter的相减,只保留正值的计数。如果每一个value都是正数,则说明magazine可以组成前者。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        ransomNote = list(ransomNote)
        magazine = list(magazine)
        while ransomNote:
            tem = ransomNote.pop()
            print tem
            if tem not in magazine:
                return False
            else:
                magazine.remove(tem)

        return True

    def canConstruct2(self, ransomNote, magazine):
        import collections
        return not collections.Counter(ransomNote) - collections.Counter(magazine)


    def canConstruct3(self, ransomNote, magazine):
        import collections
        c = collections.Counter(magazine)
        c.subtract(collections.Counter(ransomNote))
        return all(v>=0 for v in c.values())

if __name__ == '__main__':
    sol = Solution()
    s1 = "aa"
    s2 = "aab"
    print sol.canConstruct(s1, s2)
    print sol.canConstruct2(s1, s2)
    print sol.canConstruct3(s1, s2)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,766评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,788评论 0 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,837评论 18 139
  • 问题描述Given an arbitrary ransom note string and another str...
    去留无意hmy阅读 267评论 0 0
  • 终于,我从一个每天睡到自然醒的颓废青年,变成一个早起星人。 早上七点二十六。平时只是睁眼看眼表,心里想着去他妹的再...
    深井真君阅读 135评论 0 0