Python leetcode
leetcode 383. 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.
这个题目理解起来比较难,我说的意思是英语不咋滴,有些单词不太明白,怎么还有ransomNote勒索信,杂志什么的?
网上看到一个这样的理解,我们要去分别一个信是不是通过杂志里面的文字造出来的,就和侦探中的破解密码一样,可能勒索信中的字是来自杂志的,这样组合就是勒索信息。这样大概理解一些了吧。
所以说白了,就是判断ransomNote中的字符满足两个条件1.ransomNote中的字符必须在magazine中出现2.ransomNote中的字符出现次数必须不超过magazine中对应的字符次数。
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
题目的意思:
题目的意思是第一个的字符串的每个字符必须在第二个字符串中,且第一个字符串中的字符次数小于第二个字符串中该字符的次数。
#coding=utf-8
class Solution():
def canConstruct(self, ransomNote, magazine):#192ms
from collections import Counter
magDict=Counter(magazine)
for letter in ransomNote:
if letter not in magDict:
return False
else:
magDict[letter]=magDict[letter]-1
if magDict[letter]<0:
return False
return True
def canConstruct1(self, ransomNote, magazine):#184ms
from collections import Counter
ranDict=Counter(ransomNote)
magDict=Counter(magazine)
for x in ranDict:
if x not in magDict or ranDict[x]>magDict[x]:
return False
return True
def canConstruct2(self, ransomNote, magazine): #36ms
from collections import Counter
return not Counter(ransomNote)-Counter(magazine)
#Counter()的减法结果是前者中计数大于后者中,包括不存在后者中的
#说白了就是相对于后者多的部分,就是前者中后者没有的或少的
#若没有的话,就返回一个空的Counter()
s=Solution()
print s.canConstruct1('aabbbsd','aaabbbbwkskhd')