383. 赎金信
方法一:defaultdict
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
d = defaultdict(int)
for c in magazine:
d[c] += 1
for c in ransomNote:
if d[c]: # d[c] != 0
d[c] -= 1
else:
return False
return True
方法二:用列表代替字典
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
arr = [0] * 26
for c in magazine:
arr[ord(c) - 97] += 1
for c in ransomNote:
x = ord(c) - ord('a')
if arr[x]: # arr[x] != 0
arr[x] -= 1
else:
return False
return True
方法三:collections.Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return not bool(len(collections.Counter(ransomNote) - collections.Counter(magazine)))
242. 有效的字母异位词
方法一:用列表代替字典
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t): return False
arr = [0] * 26
for c in s:
arr[ord(c) - 97] += 1
for c in t:
x = ord(c) - ord('a')
if arr[x]:
arr[x] -= 1
else:
return False
return True
方法二:排序
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(list(s)) == sorted(list(t))