Leetcode刷題筆記python---贖金信
阿新 • • 發佈:2018-11-10
贖金信
題目
給定一個贖金信 (ransom) 字串和一個雜誌(magazine)字串,判斷第一個字串ransom能不能由第二個字串magazines裡面的字元構成。如果可以構成,返回 true ;否則返回 false。
(題目說明:為了不暴露贖金信字跡,要從雜誌上搜索各個需要的字母,組成單詞來表達意思。)
注意:
你可以假設兩個字串均只含有小寫字母。
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
解答
思路:
- 只要R中字元小於M中字元數量
- 遍歷,比較
程式碼:
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
if all(ransomNote.count(i)<=magazine.count(i) for i in ransomNote) :
return True
return False
結果:10%