feat: Added nodejs implementation for group anagrams
This commit is contained in:
parent
cf1d656aa5
commit
b6a9accd81
47
group-anagrams/nodejs/index.js
Normal file
47
group-anagrams/nodejs/index.js
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
/*
|
||||||
|
* Given an array of strings, group anagrams together.
|
||||||
|
*
|
||||||
|
* Example:
|
||||||
|
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
|
||||||
|
* Output: [
|
||||||
|
* ["ate","eat","tea"],
|
||||||
|
* ["nat","tan"],
|
||||||
|
* ["bat"]
|
||||||
|
* ]
|
||||||
|
*
|
||||||
|
* Note:
|
||||||
|
* All inputs will be in lowercase.
|
||||||
|
* The order of your output does not matter.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
const { assert } = require('../../util/js');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string[]} strs
|
||||||
|
* @return {string[][]}
|
||||||
|
*/
|
||||||
|
const groupAnagrams = (strs) => {
|
||||||
|
const map = {};
|
||||||
|
strs.forEach(str => {
|
||||||
|
const key = str.split('').sort().join('');
|
||||||
|
if (!map[key]) {
|
||||||
|
map[key] = [str];
|
||||||
|
} else {
|
||||||
|
map[key].push(str);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Object.values(map);
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Test Case 1
|
||||||
|
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
|
||||||
|
* Output: [
|
||||||
|
* ["ate","eat","tea"],
|
||||||
|
* ["nat","tan"],
|
||||||
|
* ["bat"]
|
||||||
|
* ]
|
||||||
|
*/
|
||||||
|
x = [ 'eat', 'tea', 'tan', 'ate', 'nat', 'bat'];
|
||||||
|
sol = [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']];
|
||||||
|
assert(JSON.stringify(groupAnagrams(x)) === JSON.stringify(sol), `Output: ${JSON.stringify(sol)}`);
|
Loading…
Reference in New Issue
Block a user