File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 시간 복잡도: O (m * n)
3
+ * - m: 문자열 개수
4
+ * - n: 각 문자열 길이
5
+ * - 각 문자열에서 빈도수 계산을 위해 O(n)이 소요되는데, 이를 각 문자열마다 진행
6
+ *
7
+ * 공간 복잡도: O (m * n)
8
+ * - m: 문자열 개수
9
+ * - n: 각 문자열 길이
10
+ * - 주어진 모든 문자열이 모두 서로 anagram을 구성하지 못한 경우, 모든 문자열 수만큼 필요함
11
+ */
12
+ class Solution {
13
+ public List <List <String >> groupAnagrams (String [] strs ) {
14
+ Map <String , List <String >> map = new HashMap <>();
15
+
16
+ for (String str : strs ) {
17
+ int [] count = new int [26 ];
18
+ for (int i = 0 ; i < str .length (); i ++) {
19
+ count [str .charAt (i ) - 'a' ]++;
20
+ }
21
+
22
+ StringBuilder sb = new StringBuilder ();
23
+ for (int i = 0 ; i < 26 ; i ++) {
24
+ sb .append ("^" ).append (count [i ]);
25
+ }
26
+ String candidate = sb .toString ();
27
+ if (!map .containsKey (candidate )) {
28
+ map .put (candidate , new ArrayList <>());
29
+ }
30
+ map .get (candidate ).add (str );
31
+ }
32
+
33
+ return new ArrayList <>(map .values ());
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments