zoukankan      html  css  js  c++  java
  • LeetCode--383--赎金信

    问题描述:

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

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

    注意:

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

    canConstruct("a", "b") -> false
    canConstruct("aa", "ab") -> false
    canConstruct("aa", "aab") -> true

    方法:

     1 from collections import Counter
     2 class Solution(object):
     3     def canConstruct(self, ransomNote, magazine):
     4         """
     5         :type ransomNote: str
     6         :type magazine: str
     7         :rtype: bool
     8         """ 
     9         dic1 = Counter(ransomNote)
    10         dic2 = Counter(magazine)
    11         #dic1,dic2 = map(Counter,(ransomNote,magazine)
    12         for key in dic1.keys():
    13             if key in dic2 and dic2[key] <dic1[key] or key not in dic2:
    14                 return False
    15         return True

    官方:set(ransomNote) 建立dic存放ransomNote词频计数,用magazine.count(val) 和 dic中的val做对比

     1 class Solution(object):
     2     def canConstruct(self, ransomNote, magazine):
     3         """
     4         :type ransomNote: str
     5         :type magazine: str
     6         :rtype: bool
     7         """
     8         x=set(i for i in ransomNote)
     9         dic={}
    10         for i in x:
    11             dic[i]=ransomNote.count(i)
    12         for k,v in dic.items():
    13             if magazine.count(k)<v:
    14                 return False
    15         return True

    2018-09-28 15:55:36

  • 相关阅读:
    django模型系统(二)
    css基础
    css进阶
    django模型系统(一)
    自定义过滤器及标签
    django模板标签
    模板变量及模板过滤器
    第六章 异常
    第三章:多态
    第三章:提高系统性能:从数据访问开始
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9719166.html
Copyright © 2011-2022 走看看