From fb21a5727e249ce000d14edf59b291b6d099ce2b Mon Sep 17 00:00:00 2001 From: borninfreedom Date: Tue, 15 Jun 2021 16:50:32 +0800 Subject: [PATCH] =?UTF-8?q?update=E8=B5=8E=E9=87=91=E4=BF=A1=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=BD=BF=E7=94=A8=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E4=BD=9C=E4=B8=BA=E5=93=88=E5=B8=8C=E8=A1=A8=E5=92=8C=E4=BD=BF?= =?UTF-8?q?=E7=94=A8defaultdict=E4=B8=A4=E7=A7=8D=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0383.赎金信.md | 49 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) 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)