본문 바로가기
programming/알고리즘 풀이

[leetcode] 49. Group Anagrams

by 몽구스_ 2021. 10. 6.
728x90

[leetcode] 49. Group Anagrams

 

 

Group Anagrams - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

[문제]

 

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.

 

 

[입출력]

 

Input: strs = ["eat","tea","tan","ate","nat","bat"]

Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

 

 

[코드]

 

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>(); 
        //키:들어간 알파벳, 값:해당하는 단어의 리스트
		
		for (int i = 0; i < strs.length; i++) {
			char[] cArr = strs[i].toCharArray();//문자열을 char배열로
			Arrays.sort(cArr);//정렬
			String key = String.valueOf(cArr);//char배열을 문자열로
			if(map.containsKey(key)) {
				map.get(key).add(strs[i]); //해당 키 값 리스트에 추가
			}else {
				ArrayList<String> list = new ArrayList<>(); 
                //새로 리스트 생성
				list.add(strs[i]);
				map.put(key, list);
			}
		}
		
		List<List<String>> result = new ArrayList<>();
		result.addAll(map.values()); //map의 모든 값 집어넣기
		
		return result;
    }
}

댓글