mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
update赎金信,添加了使用数组作为哈希表和使用defaultdict两种写法
This commit is contained in:
@ -135,8 +135,52 @@ class Solution {
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
```py
|
||||
Python写法一(使用数组作为哈希表):
|
||||
|
||||
```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):
|
||||
def canConstruct(self, ransomNote, magazine):
|
||||
"""
|
||||
@ -166,6 +210,7 @@ class Solution(object):
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
func canConstruct(ransomNote string, magazine string) bool {
|
||||
record := make([]int, 26)
|
||||
|
Reference in New Issue
Block a user