Update 0383.赎金信.md

This commit is contained in:
jianghongcheng
2023-05-05 21:05:34 -05:00
committed by GitHub
parent 5cff41ab09
commit 38bc7021c6

View File

@ -142,34 +142,27 @@ class Solution {
``` ```
Python写法一使用数组作为哈希表 (版本一)使用数组
```python ```python
class Solution: class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool: def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_count = [0] * 26
arr = [0] * 26 magazine_count = [0] * 26
for c in ransomNote:
for x in magazine: # 记录 magazine里各个字符出现次数 ransom_count[ord(c) - ord('a')] += 1
arr[ord(x) - ord('a')] += 1 for c in magazine:
magazine_count[ord(c) - ord('a')] += 1
for x in ransomNote: # 在arr里对应的字符个数做--操作 return all(ransom_count[i] <= magazine_count[i] for i in range(26))
if arr[ord(x) - ord('a')] == 0: # 如果没有出现过直接返回
return False
else:
arr[ord(x) - ord('a')] -= 1
return True
``` ```
Python写法二使用defaultdict 版本二)使用defaultdict
```python ```python
from collections import defaultdict
class Solution: class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool: def canConstruct(self, ransomNote: str, magazine: str) -> bool:
from collections import defaultdict
hashmap = defaultdict(int) hashmap = defaultdict(int)
for x in magazine: for x in magazine:
@ -177,59 +170,42 @@ class Solution:
for x in ransomNote: for x in ransomNote:
value = hashmap.get(x) value = hashmap.get(x)
if value is None or value == 0: if not value or not value:
return False return False
else: else:
hashmap[x] -= 1 hashmap[x] -= 1
return True return True
``` ```
(版本三)使用字典
Python写法三
```python
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
# use a dict to store the number of letter occurance in ransomNote
hashmap = dict()
for s in ransomNote:
if s in hashmap:
hashmap[s] += 1
else:
hashmap[s] = 1
# check if the letter we need can be found in magazine
for l in magazine:
if l in hashmap:
hashmap[l] -= 1
for key in hashmap:
if hashmap[key] > 0:
return False
return True
```
Python写法四
```python ```python
class Solution: class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool: def canConstruct(self, ransomNote: str, magazine: str) -> bool:
c1 = collections.Counter(ransomNote) counts = {}
c2 = collections.Counter(magazine) for c in magazine:
x = c1 - c2 counts[c] = counts.get(c, 0) + 1
#x只保留值大于0的符号当c1里面的符号个数小于c2时不会被保留 for c in ransomNote:
#所以x只保留下了magazine不能表达的 if c not in counts or counts[c] == 0:
if(len(x)==0): return False
return True counts[c] -= 1
else: return True
return False ```
版本四使用Counter
```python
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return not Counter(ransomNote) - Counter(magazine)
```
版本五使用count
```python
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return all(ransomNote.count(c) <= magazine.count(c) for c in set(ransomNote))
``` ```
Go Go