
์๊ฐ ๋ฐฉ์
s๋ t๋ฅผ sortํด์ ๊ฐ์์ง ์์๋ณด๋ฉด ๋ ๊ฒ ๊ฐ๋ค.
Example1์ ๊ฒฝ์ฐ
s = anagram, sorted(s) -> aaagmnr
t = nagaram, sorted(t) -> aaagmnr
๊ทธ๋์ ์ด ๋ ๊ฐ๊ฐ ๋๊ฐ์์ง ํ์ธํ๋ฉด ๋ ๊ฒ ๊ฐ๋ค
๐ป ๋ด๊ฐ ์์ฑํ ์ฝ๋
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)

* ์ ํ๋ธ๋ฅผ ํตํด ๋ค๋ฅธ ํด๊ฒฐ ๋ฐฉ๋ฒ์ ์ฐพ์๋๋ฐ ์ด๊ฒ๋ ๋ฐฐ์ฐ๋ฉด ์ข์ ๊ฒ ๊ฐ์์ ์ ์ด๋ณธ๋ค
(๋ด ๋ฐฉ์๋๋ก ์ดํดํ ๊ฑฐ๋ผ ํ๋ฆฐ ๋ด์ฉ์ด ์๋ค๋ฉด ์ง์ ํด ์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค...)
์ถ์ฒ: https://www.youtube.com/watch?v=9UtInBqnCgA&ab_channel=NeetCode
HashMap์ ์ฌ์ฉํ ๋ฐฉ๋ฒ
1. ๋จผ์ s์ t์ ๊ธธ์ด๋ฅผ ์ฒดํฌํด์ ๋ค๋ฅด๋ค๋ฉด ๋ฐ๋ก False๊ฐ ๋์ค๊ฒ ํด์ค๋ค
2. Iterate through all the keys in string s
3. Make sure the count of each of the characters are the same

๐ป Solution 1
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# ๋จผ์ ๊ธธ์ด ์ฒดํฌ
if len(s) != len(t):
return False
# hashmap ๋ง๋ค๊ธฐ
countS, countT = {}, {}
# ๊ธธ์ด๊ฐ ๊ฐ๊ธฐ ๋๋ฌธ์ len(s)๋ฅผ ์ฌ์ฉํ๋ len(t)๋ฅผ ์ฌ์ฉํ๋ ๊ฐ์
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
return countS == countT
์ฌ๊ธฐ์ for loop์ ์๋ ๋ ์ค์ ์ฝ๋๋ฅผ ์ค๋ช ํ์๋ฉด
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
s[i], t[i]๋ hashmap์ key์ด๋ค
๊ทธ๋ ๋ค๋ฉด ๊ทธ ํค์ ์กฐ๊ฑด์ ๋ถํฉํ๋ค๋ฉด ๊ณ์ incrementํด์ฃผ๋ ๋ฐฉ์์ด๋ค
์์ ๋์จ ์์๋ฅผ ๋ณด๋ฉด์ ์ค๋ช ํ์๋ฉด a๊ฐ ์ด string์ ์๋ค๋ฉด ์นด์ดํธ๋ฅผ 1 ์ถ๊ฐํด ์ฃผ๊ณ , ๋ ์ฐพ๋๋ค๋ฉด increament ํด์ฃผ๊ฒ ๋๋ค
๊ทธ๋์ ๊ฒฐ๊ตญ 3๋ฒ์ ์ฐพ๊ฒ ๋๊ธฐ์ a์ ์นด์ดํธ๋ 3์ด ๋๋ค
* Key error : key does not exist
ํ์ด์ฌ์์ ๋ฐ์ ์ด๋ฐ ์์ผ๋ก ์์ฑ์ ํ๊ฒ ๋๋ค๋ฉด, ๋ง์ฝ์ hashmap์ ์์ง ๊ทธ character๊ฐ ์กด์ฌํ์ง ์๋๋ค๋ฉด ํค ์๋ฌ๊ฐ ๋ฌ๋ค
countS[s[i]] = 1 + countS.s[i]
get(s[i], 0) -> ๋ ๋ฒ์งธ parameter๋ default value๊ฐ ๋๋ค, ๊ทธ๋ฌ๋ฏ๋ก ์ด character๊ฐ hashmap์ ์์ง ์กด์ฌํ์ง ์๋๋ค๋ฉด 0์ ๋ํด์ค
๐ป Solution 2 : ์ ์ฝ๋๋ฅผ ํ ์ค๋ก ๋ฐ๊พผ๋ค๋ฉด?
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
Counter is a data structure in Python which is a hashmap, but it counts things automatically for you
'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 746. Min Cost Climbing Stairs (Easy) [Python] (0) | 2024.02.04 |
|---|---|
| 70. Climbing Stairs (Easy) [Python] (2) | 2024.02.03 |
| 49. Group Anagrams (Medium) [Python] (0) | 2024.02.03 |
| 1. Two Sum (Easy) [Python] (0) | 2024.02.03 |
| 217. Contains Duplicate (Easy) [Python] (0) | 2024.02.03 |