Skip to content

Commit 4ee3aed

Browse files
add post '(Leetcode) 49 - Group Anagrams'
1 parent f3b8386 commit 4ee3aed

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

_posts/2024-04-23-leetcode-338.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ binary string을 charArray로 변환한 후, '1'의 갯수를 카운트 해서
4040
```java
4141
public int[] countBits(int n) {
4242
int result[] = new int[n + 1];
43-
for (int i = 0; i<=n; ++i){
43+
for (int i = 0; i <= n; i++) {
4444
int num = i;
4545
int count = 0;
46-
while (num > 0){
46+
while (num > 0) {
4747
count += num & 1;
4848
num = num >> 1;
4949
}

_posts/2024-05-25-leetcode-49.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 49 - Group Anagrams
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, algorithm, anagram, array]
6+
date: 2024-05-25 22:30:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/group-anagrams/description/](https://leetcode.com/problems/group-anagrams/description/)
17+
18+
지난번에도 anagram 과 관련된 문제를 풀었던 적이 있다. anagram은 같은 글자를 사용해 조합만 바뀐 형태를 의미한다.
19+
20+
[(Leetcode) 242 - Valid Anagram](https://algorithm.jonghoonpark.com/2024/04/24/leetcode-242)
21+
22+
## 내가 작성한 풀이
23+
24+
```java
25+
public List<List<String>> groupAnagrams(String[] strs) {
26+
List<List<String>> result = new ArrayList<>();
27+
HashMap<String, Integer> map = new HashMap<>();
28+
29+
for (String str : strs) {
30+
char[] temp = str.toCharArray();
31+
Arrays.sort(temp);
32+
String sorted = String.valueOf(temp);
33+
if (map.containsKey(sorted)) {
34+
result.get(map.get(sorted)).add(str);
35+
} else {
36+
int newIndex = result.size();
37+
List<String> newArrayList = new ArrayList<>();
38+
result.add(newArrayList);
39+
newArrayList.add(str);
40+
map.put(sorted, newIndex);
41+
}
42+
}
43+
44+
return result;
45+
}
46+
```
47+
48+
## TC, SC
49+
50+
시간 복잡도는 O(n \* m log m)이고, 공간 복잡도는 O(n + m)이다.
51+
여기서 m은 str 배열(strs)의 각 str의 평균이다.
52+
53+
먼저 입력으로 돌아온 str 배열의 크기만큼 iterate를 한다. 여기서 n이 발생되고
54+
각 str의 문자를 정렬하는데 m log m 만큼 시간이 소요된다.
55+
56+
공간 복잡도는 str를 저장하기 위한 공간이 사용되므로 여기서 O(n) 이 사용되었다고 생각하였고
57+
중간에 str를 char[]로 변환하는 과정에서 추가적인 공간이 사용되므로 여기서 O(m)이 사용되었다고 생각하였다.
58+
따라서 최종적으로 O(n + m) 으로 정리하였다.

0 commit comments

Comments
 (0)