首页 > 其他 > 详细

Leetcode 383 Ransom Note

时间:2016-12-24 07:41:05      阅读:224      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/lettuan/p/6216599.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!