码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 383 Ransom Note

时间:2016-12-24 07:43:14      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:let   contain   nbsp   for   span   比较   lis   case   lang   

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

标签:let   contain   nbsp   for   span   比较   lis   case   lang   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!