
๋ฌธ์ ํด๊ฒฐ ๊ณผ์
โ๏ธ ๋๋ง์ ๋ฐฉ์์ผ๋ก ๋ฌธ์ ์ ๋ฆฌํ๊ธฐ (=์ฒด๊ณํ)
https://leetcode.com/problems/valid-anagram/?envType=study-plan-v2&envId=top-interview-150
Valid Anagram - LeetCode
Can you solve this real interview question? Valid Anagram - Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using
leetcode.com
s์ t ๋ ๊ฐ์ ๋ฌธ์์ด์ด ์ฃผ์ด์ง ๋, t๊ฐ s์ anagram์ด๋ผ๋ฉด True, ์๋๋ฉด False๋ฅผ ๋ฐํํ๋ผ.
- | s, t | ∈ [1, 5*10^4]
- ๋ ๋ฌธ์์ด์ ์์์ ๋น๋์๊ฐ ์ ํํ ์ผ์นํ๋ฉด์ ์์๋ง ๋ค๋ฅด๋ค๋ฉด anagram์ด๋ผ๊ณ ํ๋ค.
๐ ์ด๋ค ์์ผ๋ก ์ ๊ทผํ๋๊ฐ?
์ด์ ๋ฌธ์ ์์ ํ์ฉํ Counter ํจ์๋ฅผ ์ด์ฉํ๋ค.
๐ ์๊ณ ๋ฆฌ์ฆ ์ ํ: ์ ๋ ฅ์ ํฌ๊ธฐ๋ฅผ ๋ฐํ์ผ๋ก
Counter ํจ์๋ ๋ด๋ถ์ ์ผ๋ก linear search์ด๋ค.
๐ ์์ฌ ์ฝ๋
s์ ๋น๋์์ t์ ๋น๋์๊ฐ ๊ฐ๋ค๋ฉด True๋ฅผ ๋ฐํํ๋ค.
๐ฏ ๊ตฌํ ์ฝ๋
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
๋ด ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
โฑ ์ฑ๋ฅ ์ธก์ (์๊ฐ๋ณต์ก๋/๊ณต๊ฐ๋ณต์ก๋)
Counter ํจ์๋ฅผ ํธ์ถํ์ ๋ ๊ฐ ๋ฌธ์์ด์ ๊ธธ์ด๋งํผ ๋ฌธ์๋ฅผ ์ํํ๋ค. ๋ฐ๋ผ์ ์๊ฐ ๋ณต์ก๋๋ O(n)์ด๋ค.
โ๏ธ ์ฑ๋ฅ ํ๊ณ
1์ด ์ ํ์์ O(n)์ ์ต๋ ์ ๋ ฅ์ 10^6์ด๋ค. ๋ฌธ์ ์์๋ ์ต๋ ์ ๋ ฅ์ด 5*10^4์ด๋ฏ๋ก ์ฑ๋ฅ์ ๊ด์ฐฎ๋ค.
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
๐ฏ ๊ตฌํ ์ฝ๋
๋ ๋ฌธ์์ด์ ์ ๋ ฌํ์ ๋ ์์ ํ ๋์ผํ๋ค๋ฉด, anagram์ด๋ค.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
โฑ ์ฑ๋ฅ ์ธก์ (์๊ฐ๋ณต์ก๋/๊ณต๊ฐ๋ณต์ก๋)
์ ๋ ฌ ์ฐ์ฌ์ ์๊ฐ๋ณต์ก๋์ ์ํด ๊ฒฐ์ ๋๋ค. ์ ๋ ฌ ์ฐ์ฐ์ ์๊ฐ๋ณต์ก๋๋ ์ต์ O(n log n)์ด๋ค.
๋๋ ์
๋ฐ๋ก ์ด์ ์ ํ์๋ ๋ฌธ์ ์์ ์๊ฒ๋ Counter ํจ์๋ฅผ ์ด์ฉํ์ฌ ๊ฐ๋จํ๊ฒ ํ ์ ์์๋ค.
๋ง์ฝ Counter ํจ์๋ฅผ ์ด์ฉํ์ง ์์ผ๋ ค๋ฉด,
๋์ ๋๋ฆฌ๋ฅผ ์ด์ฉํด ๊ฐ ์ํ๋ฒณ์ ๊ฐ์๋ฅผ ์นด์ดํธํ ๋ค, ๋ ๋ฌธ์์ด์ด ์ ํํ ์ผ์นํ๋์ง ์ฌ๋ถ๋ก ํด๊ฒฐํ ์ ์์์ ๊ฒ์ด๋ค.
'๐ซ ETC > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| Week 2-2. [Binary Search] 33. Search in Rotated Sorted Array (Python3) (0) | 2023.09.05 |
|---|---|
| Week 2-2. [Divide & Conquer] 148. Sort List (Python3) (0) | 2023.09.04 |
| Week 2-1. [Hash Table] 383. Ransom Note (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 |