๋ฌธ์ ํด๊ฒฐ ๊ณผ์
โ๏ธ ๋๋ง์ ๋ฐฉ์์ผ๋ก ๋ฌธ์ ์ ๋ฆฌํ๊ธฐ (=์ฒด๊ณํ)
https://leetcode.com/problems/ransom-note/?envType=study-plan-v2&envId=top-interview-150
Ransom Note - LeetCode
Can you solve this real interview question? Ransom Note - 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 ranso
leetcode.com
ransomNote์ magazine ๋ ๊ฐ์ ๋ฌธ์์ด์ด ์ฃผ์ด์ง ๋,
magazine์ ์ฒ ์๋ค์ ์ด์ฉํด ransomNote๋ฅผ ๊ตฌ์ฑํ ์ ์๋ค๋ฉด True, ์๋ค๋ฉด False๋ฅผ ๋ฐํํ๋ผ.
- | ransomNote, magazine | ∈ [1, 10^5]
- ransomNote์ magazine์ ์ํ๋ฒณ ์๋ฌธ์๋ง์ผ๋ก ์ด๋ฃจ์ด์ ธ ์๋ค.
๐ ์ด๋ค ์์ผ๋ก ์ ๊ทผํ๋๊ฐ?
์๋ฅผ ๋ค์ด magazine="aab"์ด๊ณ ransomNote="aa"๋ผ๋ฉด magazine์ ์ฒ ์๋ก ransomNote๋ฅผ ๊ตฌ์ฑํ ์ ์์ผ๋ True๋ฅผ ๋ฐํํ๋ค.
์์๋ฅผ ๋ณด์๋ง์ ๋์ ๋๋ฆฌ๊ฐ ์๊ฐ๋ฌ๋ค.
magazine์ ์ํํ๋ฉฐ ๋์ ๋๋ฆฌ์ ์ํ๋ฒณ๊ณผ ๋น๋์๋ฅผ ๋์ ํ๊ณ , ์ด์ด์ ransomNote๋ฅผ ์ํํ๋ฉฐ ๊ฐ์ ๋์ ๋๋ฆฌ์์ ๋น๋์๋ฅผ ์ฐจ๊ฐํ๋ค.
ransomNote๋ฅผ ๋ค ์ํํ์ ๋, ๋์ ๋๋ฆฌ์ ์์ ํน์ 0์ ์์ด๋ ๋์ง๋ง ์์๊ฐ ์์ผ๋ฉด ์๋๋ค.
(๋์ ๋๋ฆฌ values์ ์์๊ฐ ์๋ค๋ฉด, ransomNote์๋ ์๋ ์ํ๋ฒณ์ด magazine์๋ ์์๋ค๋ ์๋ฏธ์ด๋ค.)
๐ ์๊ณ ๋ฆฌ์ฆ ์ ํ: ์ ๋ ฅ์ ํฌ๊ธฐ๋ฅผ ๋ฐํ์ผ๋ก
ransomNote์ magazine์ ์ต๋ ๊ธธ์ด๊ฐ 10^5์ด๋ฏ๋ก linear search๋ฅผ ์ด์ฉํ๋ค.
๐ ์์ฌ ์ฝ๋
magazine์ ์ํํ๋ฉฐ:
๋์
๋๋ฆฌ์ ๊ฐ ์์์ ๋น๋์๋ฅผ ๋์ ํ๋ค.
ransomNote๋ฅผ ์ํํ๋ฉฐ:
๋์
๋๋ฆฌ์์ ๊ฐ ์์์ ๋น๋์๋ฅผ ์ฐจ๊ฐํ๋ค.
๋์
๋๋ฆฌ์ values๊ฐ ๋ชจ๋ ์์์ด๋ฉด: return True
์๋๋ฉด: return False
๐ฏ ๊ตฌํ ์ฝ๋
from collections import defaultdict
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dic = defaultdict(int)
for x in magazine:
dic[x] += 1
for x in ransomNote:
dic[x] -= 1
if all(x >= 0 for x in dic.values()): return True
else: return False
๋ด ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
โฑ ์ฑ๋ฅ ์ธก์ (์๊ฐ๋ณต์ก๋/๊ณต๊ฐ๋ณต์ก๋)
linear search๋ก ์๊ฐ๋ณต์ก๋๋ O(n)์ด๋ค.
โ๏ธ ์ฑ๋ฅ ํ๊ณ
1์ด ์ ํ์์ O(n)์ ์ต๋ ์ ๋ ฅ์ 10^6์ด๋ค. ๋ฌธ์ ์์๋ ์ต๋ ์ ๋ ฅ์ด 10^5์ด๋ฏ๋ก ์ฑ๋ฅ์ ๊ด์ฐฎ๋ค.
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
๐ฏ ๊ตฌํ ์ฝ๋
Counter ํจ์๋ฅผ ์ด์ฉํด ๋ฌธ์์ด์ ๋น๋์๋ฅผ ์นด์ดํธ ํ๋ค.
๋ ผ๋ฆฌ AND๋ ๊ต์งํฉ์ ์๋ฏธํ๋ค.
st1๊ณผ st2์ AND ๊ฒฐ๊ณผ๊ฐ st1 ์ด๋ผ๋ฉด magazine๊ณผ ransomNote์ ๊ต์งํฉ์ด ransomNote๋ผ๋ ๊ฒ์ด๋ค.
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
st1, st2 = Counter(ransomNote), Counter(magazine) # ๊ฐ ๋ฌธ์์ด ๋น๋์ ์นด์ดํธ
return st1 & st2 == st1 # ๋
ผ๋ฆฌ AND์ ๊ฒฐ๊ณผ๊ฐ st1์ด๋ผ๋ฉด True
โฑ ์ฑ๋ฅ ์ธก์ (์๊ฐ๋ณต์ก๋/๊ณต๊ฐ๋ณต์ก๋)
Counter ํจ์๋ฅผ ํธ์ถํ์ ๋ ๊ฐ ๋ฌธ์์ด์ ๊ธธ์ด๋งํผ ๋ฌธ์๋ฅผ ์ํํ๋ค. ๋ฐ๋ผ์ ์๊ฐ ๋ณต์ก๋๋ O(n)์ด๋ค.
๋๋ ์
๋ ผ๋ฆฌ ์ฐ์ฐ์๋ฅผ ํ์ฉํด๋ณธ ๊ฒฝํ์ด ๋ง์ด ์๋๋ฐ, ์ด๋ฐ ๊ฒฝ์ฐ์ ํ์ฉํ ์ ์์์ ๊นจ๋ฌ์๋ค.
'๐ซ ETC > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Week 2-2. [Divide & Conquer] 148. Sort List (Python3) (0) | 2023.09.04 |
---|---|
Week 2-1. [Hash Table] 242. Valid Anagram (Python3) (0) | 2023.09.01 |
Week 2-1. [Hash Table] 219. Contains Duplicate II (Python3) (0) | 2023.08.30 |
Week 2-1. [Hash Table] 1. Two Sum (Python3) (0) | 2023.08.30 |
Week 1-2. [Stack] 150. Evaluate Reverse Polish Notation (Python) (0) | 2023.08.29 |