Skip to content

Commit f2cc147

Browse files
committed
[7th batch] week 2 - valid anagram
1 parent b00545f commit f2cc147

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

โ€Žvalid-anagram/liza0525.pyโ€Ž

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,34 @@ def isAnagram(self, s: str, t: str) -> bool:
2323
if cnt != 0:
2424
return False
2525
return True
26+
27+
28+
29+
# 7๊ธฐ ํ’€์ด
30+
# ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
31+
# - s, t, letter_dict๋ฅผ ๋ชจ๋‘ ํ•œ loop๋‹น ํ•œ ๋ฒˆ ์”ฉ๋งŒ ๋ˆ๋‹ค.
32+
# ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
33+
# - letter_dict ์ƒ์„ฑ ์‹œ s์˜ ๊ธธ์ด(n์ด๋ผ๊ณ  ํ•  ๋•Œ)์— ์ข…์†๋œ๋‹ค.
34+
from collections import defaultdict
35+
36+
37+
class Solution:
38+
def isAnagram(self, s: str, t: str) -> bool:
39+
# s๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•  defaultdict์„ ์ƒ์„ฑ
40+
letter_dict = defaultdict(int)
41+
42+
# s์˜ ๋ฌธ์ž์—ด์„ ๋Œ๋ฉฐ ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋ฅผ ์นด์šดํŠธ
43+
for ss in s:
44+
letter_dict[ss] += 1
45+
46+
# t ๋ฌธ์ž์—ด์„ ๋Œ๋งŒ์…” ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋งŒํผ dictionary์—์„œ ๋นผ์ค€๋‹ค.
47+
for tt in t:
48+
letter_dict[tt] -= 1
49+
50+
# s, t๋ฅผ ๋Œ๋ฉฐ ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ผ ํ›„ value๋“ค์€ ๋ชจ๋‘ 0์ด ๋˜์–ด์•ผ ํ•œ๋‹ค. (์•„๋‚˜๊ทธ๋žจ ํŠน์„ฑ ์ƒ)
51+
# ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ value๊ฐ€ ์–‘์ˆ˜๋ฉด s์— ๋” ๋งŽ์•˜๊ณ , ์Œ์ˆ˜๋ฉด t๊ฐ€ ๋” ๋งŽ์•˜๋‹ค๋Š” ์˜๋ฏธ๊ฐ€ ๋จ
52+
for v in letter_dict.values():
53+
if v != 0:
54+
return False
55+
56+
return True

0 commit comments

Comments
ย (0)