๐Ÿฅž BE
home

49_Group Anagrams

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/06/27
ํƒœ๊ทธ
๊ตฌํ˜„
๋ฌธ์ž์—ด
๋‚œ์ด๋„
Medium
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

import java.util.*; class Solution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> ans = new HashMap<>(); // toCharArray() -> ๋ฌธ์ž์—ด ๋ฌธ์ž ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ // ['ABC'] -> ['A', 'B', 'C'] for (String str : strs) { char[] chars = str.toCharArray(); Arrays.sort(chars); // ๋ฌธ์ž์—ด๋กœ ์žฌ๋ณ€ํ™˜ํ•˜์—ฌ key๋กœ ํ™œ์šฉ String sorted = new String(chars); // ans์— ์—†์œผ๋ฉด key๊ฐ’๊ณผ ํ•จ๊ป˜ ๋นˆ ๋ฆฌ์ŠคํŠธ ์‚ฝ์ž… if (!ans.containsKey(sorted)) { ans.put(sorted, new ArrayList<>()); } // key๊ฐ’ ๊ฐ€์ ธ์™€์„œ ๋ฌธ์ž์—ด์— ์ถ”๊ฐ€ ans.get(sorted).add(str); } return new ArrayList<>(ans.values()); } }
Java
๋ณต์‚ฌ
toCharArray()๊ฐ€ ๋„ˆ๋ฌด ์ž˜ ์–ด์šธ๋ฆฌ๋Š” ๋ฌธ์ œ์˜€๋˜ ๊ฒƒ ๊ฐ™๋‹ค.

๋‹ค๋ฅธ ํ’€์ด (from ์ƒ๊ตฌ๋‹˜ ์ฝ”๋“œ)

import java.util.*; public class Ch06_05 { public List<List<String>> groupAnagrams(String[] strs) { Map<Integer, List<String>> map = new HashMap<>(); for (String s : strs) { int[] counts = new int[26]; for (int i = 0; i < s.length(); i++) counts[s.charAt(i) - 'a']++; int hash = Arrays.hashCode(counts); map.putIfAbsent(hash, new ArrayList<>()); map.get(hash).add(s); } List<List<String>> result = new ArrayList<>(); for (int key : map.keySet()) { result.add(map.get(key)); } return result; } }
Java
๋ณต์‚ฌ
int ๋ฐฐ์—ด ์„ ์–ธํ•ด์„œ ์•„์Šคํ‚ค๊ฐ’์œผ๋กœ count๋Š˜๋ฆฌ๋Š”๊ฑฐ๋ž‘ hash๊ฐ’์œผ๋กœ ๋งคํ•‘ํ•˜๋Š”๊ฒŒ ์ ‘๊ทผ๋ฐฉ์‹์ด ๋„ˆ๋ฌด ์ข‹์•˜๋‹ค๊ณ  ์ƒ๊ฐํ•œ๋‹ค. Integer๋กœ ์„ ์–ธํ•˜์‹œ๊ธธ๋ž˜ ์—ฅ ํ–ˆ๋Š”๋ฐ ํ’€์ด๊ฐ€ ์—„์ฒญ ์‹ ๊ธฐํ–ˆ๋‹ค.
if(!containsKey)์™€ put์„ ๋‘์ค„๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์ด putIfAbsent() ํ•˜๋‚˜๋กœ ์ค„์—ฌ์ง€๋Š” ๊ฒƒ๋„ ์•Œ๊ฒŒ๋˜์—ˆ๋‹ค.

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

toCharArray()๋กœ ๋ฌธ์ž์—ด์„ ๋ฌธ์ž ๋ฐฐ์—ด๋กœ ๋ถ„๋ฆฌํ•œ ํ›„, ์ •๋ ฌํ•ด๋ฒ„๋ฆฌ๋ฉด ์• ๋„ˆ๊ทธ๋žจ์„ ์‰ฝ๊ฒŒ ์ฐพ์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค. ์ด๋ฅผ HashMap์„ ํ™œ์šฉํ•ด์„œ ๊ทธ๋ฃนํ™”ํ•ด์ฃผ๋ฉด ๋.