컴퓨터/LeetCode

LeetCode 49 Group Anagrams Medium [Java]

이상한 나그네 2023. 12. 29. 22:00

문제: https://leetcode.com/problems/group-anagrams/

 

Group Anagrams - LeetCode

Can you solve this real interview question? Group Anagrams - Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase

leetcode.com

1. 코드

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> answer = new HashMap<>();
        for(String str : strs) {
            char[] c = str.toCharArray();
            Arrays.sort(c);
            String s = String.valueOf(c);

            if(!answer.containsKey(s))
                answer.put(s, new ArrayList<>());
            answer.get(s).add(str);
        }
        return new ArrayList<>(answer.values());
    }
}

2. 설명

Map 안에 List를 선언하여 사용할 수 있음을 잊지말자 그것만 알고 있다면 쉽게 해결할 수 있는 문제이다.