383. 赎金信
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
a = list(ransomNote)
b = list(magazine)
for i in a:
if i not in b:
return False
else:
b.remove(i)
return True
不用list,用数组
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
arr = [0] * 26
for str in magazine:
arr[ord(str) - ord('a')] += 1
for str in ransomNote:
if arr[ord(str) - ord('a')] == 0:
return False
else:
arr[ord(str) - ord('a')] -= 1
return True
用字典(更快)
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
a = list(ransomNote)
b = list(magazine)
bmap = {}
for i in b:
if i in bmap:
bmap[i] += 1
else:
bmap[i] = 1
for j in a:
if j in bmap:
bmap[j] -= 1
if bmap[j] < 0:
return False
else:
return False
return True
242. 有效的字母异位词
解法同上(数组)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
arr = [0] * 26
for str in s:
arr[ord(str) - ord('a')] += 1
for str in t:
if arr[ord(str) - ord('a')] == 0:
return False
else:
arr[ord(str) - ord('a')] -= 1
return True
list+sort 更快
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
a = list(s)
b = list(t)
a.sort()
b.sort()
return a == b