Skip to content

Commit b1310d2

Browse files
committed
Add solution for Valid Anagram
1 parent ed1e4f1 commit b1310d2

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
# Approach
3+
๋ฌธ์ž์—ด s๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” ๋”•์…”๋„ˆ๋ฆฌ word_dict๋ฅผ ๋งŒ๋“ค๊ณ ,
4+
๋ฌธ์ž์—ด t๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ word_dict์— ํ‚ค๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค.
5+
ํ‚ค๊ฐ€ ์—†์œผ๋ฉด: ์—๋„ˆ๊ทธ๋žจ ๋ถˆ๊ฐ€๋Šฅ.
6+
ํ‚ค๊ฐ€ ์žˆ์œผ๋ฉด: ๊ฐ’์—์„œ -1ํ•˜๊ณ , ์Œ์ˆ˜์ธ์ง€ ํ™•์ธํ•˜์—ฌ ์—๋„ˆ๊ทธ๋žจ ์—ฌ๋ถ€๋ฅผ ํŒ๋ณ„ํ•ฉ๋‹ˆ๋‹ค.
7+
8+
# Complexity
9+
- Time complexity: s์˜ ๊ธธ์ด๊ฐ€ N์ด๊ณ , t์˜ ๊ธธ์ด๊ฐ€ M์ผ ๋•Œ O(N+M)
10+
11+
- Space complexity: O(N+M)
12+
"""
13+
14+
from collections import defaultdict
15+
16+
17+
class Solution:
18+
def isAnagram(self, s: str, t: str) -> bool:
19+
if len(s) != len(t):
20+
return False
21+
22+
word_dict = defaultdict(int)
23+
for ch in s: # O(N)
24+
word_dict[ch] += 1
25+
26+
for ch in t: # O(M)
27+
if ch not in word_dict:
28+
return False
29+
word_dict[ch] -= 1
30+
if word_dict[ch] < 0:
31+
return False
32+
33+
return True

0 commit comments

Comments
ย (0)