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

 

posted @ 2016-12-24 04:26  lettuan  阅读(164)  评论(0编辑  收藏  举报