update赎金信,添加了使用数组作为哈希表和使用defaultdict两种写法

This commit is contained in:
borninfreedom
2021-06-15 16:50:32 +08:00
parent 999bbae8c2
commit fb21a5727e

View File

@ -135,8 +135,52 @@ class Solution {
``` ```
Python Python写法一(使用数组作为哈希表)
```py
```python
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
arr = [0] * 26
for x in magazine:
arr[ord(x) - ord('a')] += 1
for x in ransomNote:
if arr[ord(x) - ord('a')] == 0:
return False
else:
arr[ord(x) - ord('a')] -= 1
return True
```
Python写法二使用defaultdict
```python
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
from collections import defaultdict
hashmap = defaultdict(int)
for x in magazine:
hashmap[x] += 1
for x in ransomNote:
value = hashmap.get(x)
if value is None or value == 0:
return False
else:
hashmap[x] -= 1
return True
```
Python写法三
```python
class Solution(object): class Solution(object):
def canConstruct(self, ransomNote, magazine): def canConstruct(self, ransomNote, magazine):
""" """
@ -166,6 +210,7 @@ class Solution(object):
``` ```
Go Go
```go ```go
func canConstruct(ransomNote string, magazine string) bool { func canConstruct(ransomNote string, magazine string) bool {
record := make([]int, 26) record := make([]int, 26)