首页 > 代码库 > Leetcode 383 Ransom Note
Leetcode 383 Ransom Note
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") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
比较直接的思路就是把ransomNote中的字符从magazine里逐个拿出来,如果发现某个字符在magazine里面不存在也就是说明答案是False.
1 def canConstruct(self, ransomNote, magazine): 2 """ 3 :type ransomNote: str 4 :type magazine: str 5 :rtype: bool 6 """ 7 r = list(ransomNote) 8 m = list(magazine) 9 for x in r: 10 if x in m: 11 m.remove(x) 12 else: 13 return False 14 return True
另外一种方法是统计一下两个str中每个字母的个数,然后相减。如果ransomCnt - magazineCnt非空,那么答案就是False.
1 ransomCnt = collections.Counter(ransomNote) 2 magazineCnt = collections.Counter(magazine) 3 return not ransomCnt - magazineCnt
Leetcode 383 Ransom Note
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。