본문 바로가기
LeetCode

[LeetCode] 49. Group Anagrams

by JungSeung 2023. 11. 10.
728x90

https://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.

 

Example 1:

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

 

Example 2:

Input: strs = [""]
Output: [[""]]

 

Example 3:

Input: strs = ["a"]
Output: [["a"]]

 

Constraints:

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

 

Code :

var groupAnagrams = function(strs) {
	// 맵을 생성하여 정렬된 문자열을 키로, 원래 문자열을 값으로 저장
    const map = new Map();
	// 주어진 문자열 배열을 반복하여 처리
    for (let str of strs) {
    	// 문자열을 정렬하여 정렬된 문자열을 생성
        const sortedStr = str.split('').sort().join('');
		// 정렬된 문자열이 맵에 없는 경우
        if (!map.has(sortedStr)) {
        	// 정렬된 문자열을 키로 하는 새로운 배열을 맵에 추가
            map.set(sortedStr, [str]);
        } else { // 정렬된 문자열이 이미 맵에 있는 경우
        	// 해당 키에 대해 원래 문자열을 배열에 추가
            map.get(sortedStr).push(str);
        }
    }
    // 맵의 값들을 배열로 변환하여 반환
    return Array.from(map.values()); 
};

 

Solutions Code : 

var groupAnagrams = function(strs) {
	// 빈 객체를 생성하여 맵으로 활용
    let map = {}
	// 주어진 문자열 배열을 반복하여 처리
    for(let str of strs){
    	// 문자열을 정렬하여 정렬된 문자열을 생성
        let s = str.split('').sort().join('')
		// 만약 맵에 정렬된 문자열을 키로 하는 엔트리가 없으면 빈 배열로 초기화
        if(!map[s]) map[s] = []
        // 해당 키에 대해 원래 문자열을 배열에 추가
        map[s].push(str)
    }
    // 맵의 값들을 배열로 변환하여 반환
    return Object.values(map)
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 5. Longest Palindromic Substring  (0) 2023.11.15
[LeetCode] 50. Pow(x, n)  (0) 2023.11.10
[LeetCode] 48. Rotate Image  (2) 2023.11.10
[LeetCode] 47. Permutations II  (0) 2023.11.10
[LeetCode] 46. Permutations  (0) 2023.11.09