苹果面试原题:勒索信
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] * 26
for c in magazine:
arr[ord(c) - ord('a')] += 1
for c in ransomNote:
arr[ord(c) - ord('a')] -= 1
if arr[ord(c) - ord('a')] < 0:
returnFalse
returnTrue
查看完整代码,向左滑动
点击【阅读原文】,查看领扣原题。
阅读原文 关键词
字符串
内容
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。