Skip to content

Commit 1dfd2bf

Browse files
committed
Group Anagrams
1 parent 57c1e0b commit 1dfd2bf

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

group-anagrams/hjeomdev.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public List<List<String>> groupAnagrams(String[] strs) {
3+
// 감이 안 와서 해설참조
4+
// 26자리 배열을 사용해서 알파벳 카운트 -> 문자열로 만들어서 Map의 키로 사용
5+
Map<String, List<String>> anagrams = new HashMap<>();
6+
for (String str : strs) {
7+
int[] count = new int[26];
8+
for (char ch : str.toCharArray()) {
9+
int idx = ch - 'a';
10+
count[idx] = count[idx] + 1;
11+
}
12+
String key = Arrays.toString(count);
13+
if (!anagrams.containsKey(key)) {
14+
anagrams.put(key, new LinkedList<>());
15+
}
16+
List<String> words = anagrams.get(key);
17+
words.add(str);
18+
}
19+
return new ArrayList(anagrams.values());
20+
}
21+
}

0 commit comments

Comments
 (0)