Skip to content

Commit 110fff4

Browse files
committed
feat: add "Valid Anagram" solution
1 parent c0f204e commit 110fff4

File tree

1 file changed

+65
-4
lines changed

1 file changed

+65
-4
lines changed
Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,75 @@
11
"""
2-
Inputs:
2+
Inputs: two strings : s, t
33
4-
Outputs:
4+
Outputs: t ๊ฐ€ s์˜ anagram์ธ์ง€์— ๋Œ€ํ•œ ์—ฌ๋ถ€
55
66
Constraints:
77
8-
Time Complexity:
8+
1 <= s.length, t.length <= 5 * 10^4
9+
s and t consist of lowercase English letters.
910
10-
Space Complexity:
11+
Time Complexity: O(n)
12+
13+
๊ฐ ๋ฌธ์ž๋“ค์˜ ๋“ฑ์žฅ ํšŸ์ˆ˜๋งŒ ๊ฐ™์œผ๋ฉด ๋˜์ง€ ์•Š๋‚˜?
14+
15+
s์˜ Counter ์ƒ์„ฑ
16+
t์˜ Counter ์ƒ์„ฑ
17+
18+
t Counter์˜ keys() ๋Œ๋ฉด์„œ,
19+
ํ•ด๋‹น ๊ฐ’์ด s Counter ๋ฐฐ์—ด key์— ์žˆ๋Š”์ง€, ๊ทธ๋ฆฌ๊ณ  ๊ทธ key์˜ value๊ฐ’์ด ์„œ๋กœ ๊ฐ™์€์ง€ ์ฒดํฌ
20+
21+
Space Complexity: O(n)
1122
1223
"""
1324

25+
# ์ฒซ ์ฝ”๋“œ
26+
27+
from collections import defaultdict
28+
29+
30+
class Solution:
31+
def isAnagram(self, s: str, t: str) -> bool:
32+
s_dict, t_dict = defaultdict(int), defaultdict(int)
33+
34+
for ch in s:
35+
s_dict[ch] += 1
36+
37+
for ch in t:
38+
t_dict[ch] += 1
39+
40+
for key in t_dict.keys():
41+
if key not in t_dict or t_dict[key] != s_dict[key]:
42+
return False
43+
44+
return True
45+
46+
# ๋ฐ˜๋ก€ ๋ฐœ์ƒ
47+
48+
# s = "ab", t = "a"
49+
# ์–ด๋А ํ•œ ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€์œผ๋กœ ์„ธ๋ฉด ์•ˆ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค
50+
# ๋‘ count ์‚ฌ์ „์„ ๋ชจ๋‘ ๋Œ์•„์•ผํ• ๋“ฏ. t keys()๋ฅผ ๊ธฐ์ค€์œผ๋กœ๋งŒ ๋Œ๋ฉด true๊ฐ€ ๋‚˜์™€๋ฒ„๋ฆผ. ๋‹ต์€ false์ธ๋ฐ
51+
52+
53+
from collections import defaultdict
54+
55+
56+
class Solution:
57+
def isAnagram(self, s: str, t: str) -> bool:
58+
s_dict, t_dict = defaultdict(int), defaultdict(int)
59+
60+
for ch in s:
61+
s_dict[ch] += 1
62+
63+
for ch in t:
64+
t_dict[ch] += 1
65+
66+
for key in t_dict.keys():
67+
if key not in s_dict or t_dict[key] != s_dict[key]:
68+
return False
69+
70+
for key in s_dict.keys():
71+
if key not in t_dict or t_dict[key] != s_dict[key]:
72+
return False
73+
74+
return True
1475

0 commit comments

Comments
ย (0)