Scribbling

[Java 101] 49. Group Anagrams with HashMap, StringBuilder 본문

Computer Science/Java

[Java 101] 49. Group Anagrams with HashMap, StringBuilder

focalpoint 2023. 2. 14. 03:55
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List> map = new HashMap<>();
        for (String str: strs) {
            int[] count = new int[26];
            Arrays.fill(count, 0);
            for (char c: str.toCharArray()) {
                count[c - 'a']++;
            }
            StringBuilder sb = new StringBuilder();
            for (int i=0; i<26; i++) {
                sb.append("#");
                sb.append(count[i]);
            }
            String key = sb.toString();
            if (!map.containsKey(key))
                map.put(key, new ArrayList<String>());
            map.get(key).add(str);
        }
        return new ArrayList(map.values());
    }
}