本文共 884 字,大约阅读时间需要 2 分钟。
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.canConstruct("a", "b") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("aa", "aab") -> true
思路: 这道题就是判断第一个字符串的每一个字符,是否都在第二个字符串中存在.(需要比较重复出现次数)
所以用set()找出有哪些字符,用count()找出每个字符存在几个,然后与第二个字符串比较即可.
class Solution(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ for i in set(ransomNote): if ransomNote.count(i) > magazine.count(i): return False return True
转载地址:http://iprbb.baihongyu.com/