Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit46333ca

Browse files
committed
Added improved JS solution for problem 49
1 parent5356af7 commit46333ca

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

‎javascript/49-Group-Anagrams.js‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,58 @@
1+
//////////////////////////////////////////////////////////////////////////////
2+
// Hash Each Word
3+
// Time: O(n*max(w))
4+
// Space: O(n*max(w))
5+
// This solution is faster than sorting each word.
6+
//////////////////////////////////////////////////////////////////////////////
7+
8+
/**@const {!Object<string, number>} */
9+
constCODES={
10+
a:0,b:1,c:2,d:3,e:4,f:5,g:6,h:7,i:8,j:9,
11+
k:10,l:11,m:12,n:13,o:14,p:15,q:16,r:17,
12+
s:18,t:19,u:20,v:21,w:22,x:23,y:24,z:25
13+
};
14+
15+
/**
16+
*@param {string[]} words
17+
*@return {string[][]}
18+
*/
19+
functiongroupAnagrams(words){
20+
21+
constmap=Object.create(null);
22+
for(constwordofwords){
23+
consthash=hashWord(word);
24+
if(!(hashinmap)){
25+
map[hash]=[];
26+
}
27+
map[hash].push(word);
28+
}
29+
30+
constgroups=[];
31+
for(constkeyinmap){
32+
groups.push(map[key]);
33+
}
34+
returngroups;
35+
}
36+
37+
/**
38+
*@param {string} word
39+
*@return {string}
40+
*/
41+
functionhashWord(word){
42+
consthash=newArray(26).fill(0);
43+
for(constchofword){
44+
++hash[CODES[ch]];
45+
}
46+
returnhash.toString();
47+
}
48+
49+
//////////////////////////////////////////////////////////////////////////////
50+
// Sort Each Word
51+
// Time: O(n*max(w)*log(max(w)))
52+
// Space: O(n*max(w))
53+
// This solution is slower than hashing each word.
54+
//////////////////////////////////////////////////////////////////////////////
55+
156
/**
257
*@param {string[]} strs
358
*@return {string[][]}
@@ -8,7 +63,6 @@ const groupAnagrams = (strs) => {
863
for(leti=0;i<strs.length;i++){
964
constsorted=strs[i].split("").sort().join("");
1065
//! we are just splitting the string and sorting it and joining it back
11-
console.log(sorted);
1266
if(map.has(sorted)){
1367
map.get(sorted).push(strs[i]);//! if the map has the sorted string, we push the string into the array
1468
}else{

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp