1. ๋ฌธ์ œ : https://leetcode.com/problems/group-anagrams/description/

 

2. ํ’€์ด

key๋ฅผ ๋งŒ๋“ค์–ด ํ™œ์šฉํ•˜๋Š”๊ฒŒ ์ค‘์š”

key๊นŒ์ง€ ๋น„๊ตํ•  ํ•„์š” x

 

3. ์ฝ”๋“œ

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, Integer> map = new HashMap<>();
        List<List<String>> items = new ArrayList();
        int k = 0;

        for(String str : strs){
            // key ์ƒ์„ฑํ•˜๊ธฐ.
            char[] strChars = str.toCharArray();
            Arrays.sort(strChars);
            String key = new String(strChars);

            if(map.get(key) != null){
                int n = map.get(key);
                List<String> item = items.get(n);
                item.add(str);
                items.set(n, item);
            }else{
                map.put(key, k++);
                ArrayList<String> item = new ArrayList<>();
                item.add(str);
                items.add(item);
            }
        }
        return items;

    }    
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ