File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments