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, typically using all the original letters exactly once.
strs
List<List<String>>
)정렬한 문자열로 구분하기
Map 자료구조 사용
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> letterToElements = new HashMap<>();
for (String str : strs) {
String sortedLetter = sort(str);
List<String> elements = letterToElements.getOrDefault(sortedLetter, new ArrayList<>());
elements.add(str);
letterToElements.put(sortedLetter, elements);
}
return new ArrayList<>(letterToElements.values());
}
private String sort(String str) {
char[] sortedArray = str.toCharArray();
Arrays.sort(sortedArray);
return String.valueOf(sortedArray);
}
}