[LeetCode] Top Interview 150 Problems Solving # 383 Ransom Note
Understanding the Problem
There are two strings give as parameters, ransomNote
and magazine
. I need to return True
if ransomNote
can be constructed with the characters of magazine
. As an example,
# sample 1
ransomNote = "ba"
magazine = "aab"
this sample above is True
because ransomNote characters can be made with “ab” from magazine
, but,
# sample 2
ransomNote = "baa"
magazine = "ab"
this case comes with the output of False
as magazine
characters lack to form ransomNote
.
Approach
I was in between the decisions. One was to go with pop()
method, which I do not know why I like this name of the method, and the other one was to go with remove()
, which I recently got familiar with. But after a while trying to solve the problem, pop()
was not friendly with me so I went with remove()
.
I would chage first the ransomNote
into a list in the form of which will be easier for me to handle with remove()
, the for looping magazine
string to check characters.
Solution
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
l = list(ransomNote)
for c in magazine:
if c in l:
l.remove(c)
if len(l) == 0:
return True
return False
Characters from magazine
will be checked if the same character exists in list(ransomNote)
. If it does exist, the character will be remove from the list so the miss match won’t happen.
Finally, if the list has length 0, it means every character of ransomNone
was used in magazine
, thus it fulfills the instruction, which finishes by returning True
Reflection
Other people were solving the problem with count()
method, and some other were returning the function quicker by comparing the characters so the function will not have to check every character until the very end, which I had never thought of while solving this problem. I know I could do better though, hence will try it with shorter time and better efficiency.