leetcode 383. Ransom Note 赎金信 python 多种思路,一行代码(all() , set() 操作)

class Solution:
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        # method one 用内置函数做出字典影响效率
        # dic1 , dic2 = collections.Counter(ransomNote) , collections.Counter(magazine)
        # for key1 , value1 in dic1.items():
        #     value2 = dic2.get(key1)
        #     if value2 == None or value2 < value1:
        #         return False
        # return True



        # method two  代码简洁,但是有冗余操作
        # return all([ransomNote.count(i) <= magazine.count(i)  for i in  set(ransomNote)]) 


        # method three   只需要一次遍历,高效
        for i in ransomNote:
            if i in magazine:
                magazine = magazine.replace(i,'',1)
            else:
                return False
        return True

猜你喜欢

转载自blog.csdn.net/huhehaotechangsha/article/details/80831513