每日leetcode-数组-383. 赎金信

分类:字符串-字符的统计

题目描述:

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

 解题思路:

对magazines中的字符进行遍历,相同字母个数加一写进字典,再对ransom中的字符进行遍历,依次减1  如果出现不在字典中的字母或者有字母个数出现-1,则返回false ,否则,返回true

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        a = {}
        for i in magazine:
            if i not in a:
                a[i] = 1
            else:
                a[i] += 1
        for j in ransomNote:
            if j not in a:
                return False
            else:
                a[j] -= 1
            if a[j] < 0:
                return False
        return True

时间复杂度O(n)

空间复杂度O(x)  x为字符个数,小写字母总共26个,最大为26.

用counter简化代码:

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        a = Counter(magazine)
        for j in ransomNote:
            a[j] -= 1
            if a[j] < 0:
                return False
        return True
原文地址:https://www.cnblogs.com/LLLLgR/p/14930907.html