383. Ransom Note --leetcode


编程练习,多多思考。我的思路是使用字典,通过记录字符对应的值来完成,后来发现 leetcode 上有许多好的思路,很好的利用 python 的优势,学习到了许多。

题目

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

python解法

我觉得这三种其实思路都是一样的,只是在代码编写方面不同,第二种和第三种代码编写方式要好很多,速度也更快,学习到了许多

使用字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
dic = {}
for i in magazine:
if i in dic:
dic[i] += 1
else:
dic[i] = 1

for j in ransomNote:
if j in dic:
dic[j] -= 1
if dic[j] < 0:
return False
else:
return False
return True

使用 python 的 set 和 count()

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True

使用 collections.Counter()

1
2
def canConstruct(self, ransomNote, magazine):
return not collections.Counter(ransomNote) - collections.Counter(magazine)