Skip to content

Commit dfd36e7

Browse files
committed
add valid-anagram solution
1 parent 8460438 commit dfd36e7

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

valid-anagram/jongwanra.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/valid-anagram/
4+
5+
[Brain Storm]
6+
아나그램인 경우, true, 아니면 false 반환
7+
동일한 알파벳이 중복되어 사용될 수 있다.
8+
9+
[Plan]
10+
1. s에 대해 for-loop을 순회하며 alphabet-count 형태로 map을 만든다.
11+
2. t에 대해 for-loop을 순회한다.
12+
2-1. t의 alphabet이 alphabet-count > 0 인 경우, count -= 1을 한다.
13+
2-2. 없는 경우, false로 return 한다.
14+
3. alphabet-count 가 빈 경우 true 그렇지 않으면 false를 반환한다.
15+
16+
[Complexity]
17+
t.length = N
18+
s.length = M
19+
20+
Time: O(N + M)
21+
Space: O(M)
22+
"""
23+
24+
25+
class Solution:
26+
def isAnagram(self, s: str, t: str) -> bool:
27+
alphabet_to_count = {}
28+
for alphabet in s:
29+
alphabet_to_count[alphabet] = alphabet_to_count.get(alphabet, 0) + 1
30+
31+
for alphabet in t:
32+
count = alphabet_to_count.get(alphabet, -1)
33+
if count == -1:
34+
return False
35+
36+
count -= 1
37+
if count == 0:
38+
alphabet_to_count.pop(alphabet)
39+
else:
40+
alphabet_to_count[alphabet] = count
41+
42+
return len(alphabet_to_count) == 0
43+
44+
45+
46+
sol = Solution()
47+
# Normal Case
48+
print(sol.isAnagram("anagram", "nagaram"))
49+
print(sol.isAnagram("rat", "car"))
50+

0 commit comments

Comments
 (0)