zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):第383题:赎金信:给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。

    题目:

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

    (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

    注意:

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

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

    思路:

    使用哈希表。

    程序:

    class Solution:
        def canConstruct(self, ransomNote: str, magazine: str) -> bool:
            if not ransomNote and magazine:
                return True
            if ransomNote and not magazine:
                return False
            if not ransomNote and not magazine:
                return True
            myHashMap = {}
            for index1 in range(len(magazine)):
                if magazine[index1] not in myHashMap:
                    myHashMap[magazine[index1]] = 1
                else:
                    myHashMap[magazine[index1]] += 1
            for index2 in range(len(ransomNote)):
                if ransomNote[index2] in myHashMap and myHashMap[ransomNote[index2]] > 0:
                    myHashMap[ransomNote[index2]] -= 1
                else:
                    return False
            return True
    

      

  • 相关阅读:
    CloudFoundry 中的GoRouter性能測试
    Android-SharedPreferences
    Oracle 闪回表实验
    使用Jfree实现吧条形图,java代码
    ZOJ Monthly, October 2010 ABEFI
    熟知CDN
    看,2015阿里巴巴视觉设计人员面临的问题招收学校
    于win7使用虚拟磁盘隐藏文件
    2015广东工业大学ACM学校巡回赛 I 游戏高手 (如压力dp)
    spring mvc 错误摘要--。位。
  • 原文地址:https://www.cnblogs.com/zhuozige/p/13024494.html
Copyright © 2011-2022 走看看