类型:字符串
-
- 赎金信 💚
https://leetcode-cn.com/problems/ransom-note/
❓ 判断杂志 magazine 中的字符能否构成赎金信 ransom。
💡 哈希
遍历 magazine,构建哈希表,字符为键,出现次数为值。
遍历 ransom,检验各个字符的出现次数,
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: hashMap = {} for c in magazine: if c in hashMap: hashMap[c] += 1 else: hashMap[c] = 1 for c in ransomNote: if not c in hashMap: return False elif hashMap[c] == 1: del hashMap[c] else: hashMap[c] -= 1 return True时间复杂度:O(m + n),空间复杂度:O(m)