383. Ransom Note [easy] (Python)

题目链接

https://leetcode.com/problems/ransom-note/

题目原文

> Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 



> Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

题目翻译

给定一个勒索信字符串,和一个包含所有杂志里字符的字符串,写一个函数,当该信可以被所有杂志里字符构成时返回true,否则返回false。杂志字符串里每个字符只能使用一次。
注意:假定两个字符串都只包含小写字符。

思路方法

思路一

计算两个字符串每个字母出现的次数再比较即可。可以用数组或字典保存每个字母出现的次数,对于两个字符串分别用加法和减法统计字母出现次数。下面的代码用了数组。

代码

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        if len(ransomNote) > len(magazine):
            return False
        letters = [0] * 26
        for c in magazine:
            letters[ord(c) - 97] += 1
        for c in ransomNote:
            letters[ord(c) - 97] -= 1
            if letters[ord(c) - 97] < 0:
                return False
        return True

思路二

与思路一相同,不过用的字典。

代码

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        if len(ransomNote) > len(magazine):
            return False
        letters = {}
        for c in magazine:
            letters[c] = letters[c] + 1 if c in letters else 1
        for c in ransomNote:
            if c not in letters:
                return False
            letters[c] -= 1
            if letters[c] < 0:
                return False
        return True

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52387920

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值