Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that Would return true if the ransom note can be constructed from the magazines; Otherwise, it'll return false.
The magazine string can is used once in your ransom note.
Note:
You may assume this both strings contain only lowercase letters.
Canconstruct ("A", "B")-Falsecanconstruct ("AA", "AB"), falsecanconstruct ("AA", "AaB"), True
The more straightforward idea is to take the characters from the Ransomnote to the magazine, and if you find that a character doesn't exist in magazine, that means the answer is false.
1 defcanconstruct (Self, Ransomnote, magazine):2 """3 : Type Ransomnote:str4 : Type Magazine:str5 : Rtype:bool6 """7R =list (ransomnote)8m =List (magazine)9 forXinchr:Ten ifXinchm: One m.remove (x) A Else: - returnFalse - returnTrue
Another way is to count the number of each letter in the two Str and subtract it. IfransomCnt - magazineCnt非空,那么答案就是False.
1 ransomcnt = collections. Counter (ransomnote)2 magazinecnt = collections. Counter (magazine)3return not ransomcnt-magazinecnt
Leetcode 383 Ransom Note