題目描述:
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
題目大意:ransom Note構(gòu)成一個字符串,magazines構(gòu)成一個字符串,對于ransom Note字符串,能否由magazines中的字符構(gòu)成,其中magazines中的每個字符只能使用一次。
思路:
1.ransomNote.length > magazines.length 顯然,ransomNote不能由magazines構(gòu)成
2.ransomNote中出現(xiàn)的每一個字符進行統(tǒng)計,統(tǒng)計其出現(xiàn)次數(shù),對magazines中的字符也進行同樣的統(tǒng)計。對每一個相同字符,ransomNote中出現(xiàn)的次數(shù)小于等于magazines中出現(xiàn)的次數(shù)時, ransomNote可由magazines構(gòu)成
代碼:
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
if len(ransomNote) > len(magazine):
return False
a = dict()
b = dict()
for i in range(len(ransomNote)):
a[ord(ransomNote[i]) - ord('a')] = 0
for x in range(len(magazine)):
b[ord(magazine[x]) - ord('a')] = 0
for i in range(len(ransomNote)):
a[ord(ransomNote[i]) - ord('a')] +=1
for x in range(len(magazine)):
b[ord(magazine[x]) - ord('a')] +=1
for i in range(len(ransomNote)):
if b.has_key(ord(ransomNote[i]) - ord('a')):
if a[ord(ransomNote[i]) - ord('a')] > b[ord(ransomNote[i]) - ord('a')]:
return False
else:
pass
else:
return False
return True