LintCode 1503

勒索信

题目描述
给定一个任意的表示勒索信内容的字符串,和另一个字符串表示杂志的内容,写一个方法判断能否通过剪下杂志中的内容来构造出这封勒索信,若可以,返回 true;否则返回 false。
杂志字符串中的每一个字符仅能在勒索信中使用一次。
你可以认为两个字符串都只包含小写字母。

扫码免费做题
↓↓↓

样例 1
输入 : ransomNote = "aa", magazine = "aab"输出 : true解析 : 勒索信的内容可以有杂志内容剪辑而来
样例 2
输入 : ransomNote = "aaa", magazine = "aab"输出 : false解析 : 勒索信的内容无法从杂志内容中剪辑而来
解题思路
开一个arr数组,遍历magazine的内容记录每个字符出现的个数,然后继续遍历ransomNote的内容减去相应字符的个数,若出现某个字符的个数小于0,则返回False
源代码
classSolution:""" @param ransomNote: a string @param magazine: a string @return: whether the ransom note can be constructed from the magazines """defcanConstruct(self, ransomNote, magazine):# Write your code here arr = [0] * 26for c in magazine: arr[ord(c) - ord('a')] += 1for c in ransomNote: arr[ord(c) - ord('a')] -= 1if arr[ord(c) - ord('a')] < 0:returnFalsereturnTrue
查看完整代码,向左滑动
点击【阅读原文】,查看领扣原题
继续阅读
阅读原文