題目:原題鏈接(簡單)
解法 | 時間複雜度 | 空間複雜度 | 執行用時 |
---|---|---|---|
Ans 1 (Python) | O(m+n) | O(n) | 72ms (51.08%) |
Ans 2 (Python) | O(m+n) | O(1) | 80ms (40.28%) |
Ans 3 (Python) | – | O(1) | 40ms (98.67%) |
LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。
解法一(哈希表實現):
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap = {}
# 遍歷統計雜誌中個字母的數量
for c in magazine:
if c not in hashmap:
hashmap[c] = 1
else:
hashmap[c] += 1
# 遍歷贖金信判斷雜誌中字母數量是否充足
for c in ransomNote:
if c not in hashmap:
return False
elif hashmap[c] <= 0:
return False
else:
hashmap[c] -= 1
else:
return True
解法二(24個字母是固定的):
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
hashmap = [0] * 26
# 遍歷統計雜誌中個字母的數量
for c in magazine:
hashmap[ord(c) - 97] += 1
# 遍歷贖金信判斷雜誌中字母數量是否充足
for c in ransomNote:
if hashmap[ord(c) - 97] <= 0:
return False
else:
hashmap[ord(c) - 97] -= 1
else:
return True
解法三(直接從雜誌中裁剪):
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
for c in ransomNote:
if c in magazine:
magazine = magazine.replace(c, "", 1)
else:
return False
else:
return True