알고리즘/Array

그룹 애너그램

e-pd 2023. 9. 29. 01:07

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

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

public class GroupAnagram {

    public List<List<String>> solve(String[] strs) {
        // 정렬을 한다.
        Map<String, List<String>> result = new HashMap<>();
        for (String str : strs) {
            char[] inputChars = str.toCharArray();
            Arrays.sort(inputChars);
            result.computeIfAbsent(new String(inputChars), k -> new ArrayList<>()).add(str);
        }

        return new ArrayList<>(result.values());
    }
}

 

 

문자를 정렬하면 같은 문자로 취합이 된다.

정렬된 문자를 키로 취합된 문자를 리스트로 받으면 되는 문제이다.