|
| 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