[nb] Sync
This commit is contained in:
		
							
								
								
									
										47
									
								
								exercises/group-anagrams/nodejs/index.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										47
									
								
								exercises/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)}`); | ||||
		Reference in New Issue
	
	Block a user