Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- 1 <= ransomNote.length, magazine.length <= 105
- ransomNote and magazine consist of lowercase English letters.
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dict_mag = dict()
for s in magazine:
dict_mag[s] = dict_mag.get(s, 0) +1
print('dict_mag', dict_mag)
for st in ransomNote:
if st not in dict_mag:
return False
if dict_mag[st] == 0:
return False
dict_mag[s] -= 1
return True
통과된 풀이
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dict_ran = collections.Counter(ransomNote)
dict_mag = collections.Counter(magazine)
for key, value in dict_ran.items():
if key not in dict_mag or value > dict_mag[key]:
return False
return True
신박한 풀이
완전 한줄짜리 풀이
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return all( ransomNote.count(x) <= magazine.count(x) for x in set(ransomNote) )
비슷한 원리인데 좀더 긴거
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True
'💻 LEETCODE' 카테고리의 다른 글
[LEETCODE] 14. Longest Common Prefix (0) | 2022.11.22 |
---|---|
[LEETCODE] 9. Palindrome Number (0) | 2022.11.22 |
[LEETCODE] 876. Middle of The Linked List (0) | 2022.11.22 |
[LEETCODE] 1342. Number of Steps to Reduce a Number to Zero (0) | 2022.11.16 |
[LEETCODE] 412. Fizz Buzz (1) | 2022.11.15 |
댓글