1. 문제 및 예시
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
** All inputs will be in lowercase.
** The order of your output does not matter.
2. 풀이
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
const mapStrs = new Map();
for (let i = 0; i < strs.length; i++) {
let str = strs[i];
let sortedStr = str.split('').sort().join('');
if(mapStrs.size > 0 && mapStrs.has(sortedStr)){
mapStrs.get(sortedStr).push(str);
}else{
mapStrs.set(sortedStr,[str])
}
}
let result = [];
for(let list of mapStrs){
result.push(list[1]);
}
return result;
};
** 단어내 알파벳을 정렬시켜 맵에 담아두고 같은 알파벳을 가진 단어를 찾는다.
3. 결과
101 / 101 test cases passed.
Status: Accepted
Runtime: 240 ms
Memory Usage: 45.2 MB
반응형
'Programming' 카테고리의 다른 글
[LeetCode] [Easy] [JS] 876. Middle of the Linked List (0) | 2020.04.09 |
---|---|
[LeetCode] [JS] Apr 7th. Counting Elements (0) | 2020.04.08 |
[LeetCode] [Easy] [JS] 122. Best Time to Buy and Sell Stock II (0) | 2020.04.06 |
[LeetCode] [Easy] [JS] 53. Maximum Subarray (0) | 2020.04.04 |
[DynamicProgramming] Kadane's Algorithm(카데인 알고리즘) (0) | 2020.04.04 |