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. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan
leetcode.com
동일한 문자로 구성된 문자열을 묶어주는 문제이다. 문자를 분해한 이후 정렬해주면 그 구성을 확인할 수 있다. 이 확인한 결과를 Map 구조의 키로 이용해주어 각 단어들의 리스트를 만들어 줄 수 있다. 아래의 코드와 같이 해결해 줄 수 있다.
import java.util.*;
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for(String str: strs){
char[] c = str.toCharArray();
Arrays.sort(c);
String reArrange = new String(c);
if(!map.containsKey(reArrange)){
map.put(reArrange, new ArrayList<>());
}
map.get(reArrange).add(str);
}
return new ArrayList<>(map.values());
}
}
'Algolithm-Leetcode > Arrays & Hashing' 카테고리의 다른 글
| Top K Frequent Elements (0) | 2026.08.23 |
|---|---|
| Contains Duplicate (0) | 2026.08.14 |
| Valid Anagram (0) | 2026.08.07 |
| Two Sum (0) | 2026.07.21 |