https://leetcode.com/problems/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, typically using all the original letters exactly once.
consists of lowercase English letters.
anagram은 단어들을 알파벳순으로 정렬했을 때 결과가 같으면 anagram이다. 반복문을 한번만 돌고 해결하기 위해서 HashMap을 이용했다.
import java.util.*;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> answer = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
String sorted = String.valueOf(arr);
if (map.containsKey(sorted))
map.get(sorted).add(s);
else
map.put(sorted, new ArrayList<>(Arrays.asList(s)));
}
answer.addAll(map.values());
return answer;
}
}