Leetcode 383 Ransom Note

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode(383)Ransom Note

LeetCode 383 Ransom Note

LeetCode 383 Ransom Note

LeetCode_383. Ransom Note

[LeetCode]383. Ransom Note 解题小结

Leetcode 383 Ransom Note