[LC BC] Group Anagrams 52

YJ·4일 전

LeetCode Bootcamp

목록 보기
4/6

https://www.hackerrank.com/contests/leetcode-bootcamp-week-1/challenges/group-anagrams-52-1/problem?isFullScreen=true

문제

주어진 배열에서 anagram 끼리 모아서 출력하기

답안

public static List<String> groupAnagrams(List<String> strs) {
	Map<List<Character>, List<String>> map = new HashMap<>();
	for (String str: strs) {
		List<Character> tmp = new ArrayList<>();
		for (char ch: str.toCharArray()) {
			tmp.add(ch);
		}
		Collections.sort(tmp);
		List<String> res = map.getOrDefault(tmp, new ArrayList<>());
		res.add(str);
		map.remove(tmp);
		map.put(tmp, res);
	}
	List<String> answer = new ArrayList<>();
	for (List<String> entities: map.values()) {
		String entity = "";
		Collections.sort(entities);
		for (String str: entities) {
			entity += str + " ";
		}
		answer.add(entity.substring(0, entity.length()-1));
	}
	Collections.sort(answer);
	return answer;    
}

메모

뭐 차근차근하니 됐다.. 더 깔끔하게 만드는 법이 있을까

profile
Hello

0개의 댓글