diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 23e2c5fd..5374a08f 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -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)