We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 596ce89 commit 4a966b4Copy full SHA for 4a966b4
valid-anagram/hu6r1s.py
@@ -0,0 +1,33 @@
1
+from collections import defaultdict
2
+
3
+class Solution:
4
+ """
5
+ 1. Counter를 이용한 풀이
6
+ - Counter로 풀이하였으나 s, t 길이가 서로 다를 때 해결되지 않음
7
+ 2. defaultdict 활용 풀이
8
+ - 똑같이 개수 세고 제외
9
10
+ TC
11
+ - s의 길이: n, t의 길이: n (조건상 같거나 비교 가능한 길이)
12
+ - 첫 번째 for 루프: O(n) → s의 모든 문자를 순회
13
+ - 두 번째 for 루프: O(n) → t의 모든 문자를 순회
14
+ - 총 시간 복잡도 = O(n)
15
16
+ SC
17
+ - counter는 알파벳 개수를 세는 용도로만 사용됨
18
+ - 공간 복잡도 = O(1)
19
20
+ def isAnagram(self, s: str, t: str) -> bool:
21
+ counter = defaultdict(int)
22
23
+ for i in s:
24
+ counter[i] += 1
25
26
+ for i in t:
27
+ if i not in counter:
28
+ return False
29
+ counter[i] -= 1
30
31
+ if counter[i] == 0:
32
+ del counter[i]
33
+ return False if counter else True
0 commit comments