zoukankan      html  css  js  c++  java
  • LeetCode383赎金信

    # coding:utf-8
    """
    Name : LeetCode383.py
    Author  : qlb
    Contect : 17801044486@163.com
    Time    : 2021/2/6 9:32
    Desc:赎金信
    """
    # 解题思路 和四数相加思路类似
    # 1分为两部分 将两个字符串分别按照 key(字符) value(字符出现的次数)存储在两个哈希表中
    # 2 遍历 保存ransomNote的哈希表 ransomNote每个字符出现的次数小于等于该字符在magazine中出现的次数即可
    
    #Solution1 原始写法
    import collections
    
    
    class Solution1:
        def canConstruct(self, ransomNote: str, magazine: str) -> bool:
            bigDic = {}
            smallDic = {}
            for s1 in magazine:
                if s1 in bigDic:
                    bigDic[s1] += 1
                else:
                    bigDic[s1] = 1
            for s2 in ransomNote:
                if s2 in smallDic:
                    smallDic[s2] += 1
                else:
                    smallDic[s2] = 1
            boolCount = 0
            for k,v in smallDic.items():
                if k in bigDic:
                    if v <= bigDic[k]:
                        boolCount += 1
            if boolCount == len(smallDic):
                return True
            else:
                return False
    
    # Solution2 效率更高的写法
    class Solution:
        def canConstruct(self, ransomNote: str, magazine: str) -> bool:
            bigDic = collections.Counter(magazine)
            smallDic = collections.Counter(ransomNote)
            for k,v in smallDic.items():
                if bigDic.get(k,-1) < v:
                    return False
            return True
  • 相关阅读:
    团队作业六
    团队作业五
    团队作业(四)
    团队作业(三)
    团队作业二
    宇宙圣斗士队介绍
    团队作业之七
    团队作业之六
    团队作业五
    奥特曼小分队之四(Work Breakdown Structure)
  • 原文地址:https://www.cnblogs.com/cnugis/p/14380716.html
Copyright © 2011-2022 走看看