


class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
# 初始化字符计数数组(小写字母共26个)
count = [0] * 26
# 统计magazine中各字符的出现次数
for c in magazine:
count[ord(c) - ord('a')] += 1 # 将字符映射到数组索引(如'a'→0,'b'→1)
# 检查ransomNote中的字符是否可用
for c in ransomNote:
index = ord(c) - ord('a')
count[index] -= 1 # 消耗该字符
if count[index] < 0: # 若字符不足,直接返回False
return False
return True # 所有字符均满足条件
538

被折叠的 条评论
为什么被折叠?



