[M] 49. Group Anagrams

YJ·7일 전

leetcode

목록 보기
73/100

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

문제

string 배열이 주어지면, 같은 anagram 끼리 묶기

답안

public List<List<String>> groupAnagrams(String[] strs) {
	HashMap<String, List<String>> map = new HashMap<>();
	for (String str : strs) {
		char[] chars = str.toCharArray();
		Arrays.sort(chars);
		String key = new String(chars);
		List<String> tmp = map.getOrDefault(key, new ArrayList<>());
		tmp.add(str); 
		map.put(key, tmp);
	}
	List<List<String>> answer = new ArrayList<>();
	for (String key : map.keySet()) {
		answer.add(map.get(key));
	}
	return answer;
}

sort 해서 String 으로 만든 값을 hashmap 키로 사용

메모

computeIfAbsent() 라는 야르한 함수..

map.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
profile
Hello

0개의 댓글