Skip to content

Commit 53ba8fc

Browse files
committed
sadie100: group anagrams solution
1 parent d9a4fc9 commit 53ba8fc

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

โ€Žgroup-anagrams/sadie100.tsโ€Ž

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
strs์˜ ๋ฌธ์ž์—ด๋“ค์„ ๋“ฑ์žฅ๋นˆ๋„๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ณ„์‚ฐํ•œ ํŠน์ˆ˜ ๋ฌธ์ž์—ด๋กœ ์ „ํ™˜ํ•˜๊ณ  ๊ฐ™์€ ๊ฒƒ๋ผ๋ฆฌ ๋ฌถ๋Š”๋‹ค.
3+
4+
์‹œ๊ฐ„๋ณต์žก๋„ : O(N * K) - N์€ strs์˜ ๊ฐœ์ˆ˜, K๋Š” strs์˜ ๊ธธ์ด. N ์ˆœํšŒ ์•ˆ์— K ์ˆœํšŒ
5+
*/
6+
7+
function groupAnagrams(strs: string[]): string[][] {
8+
const anagramMap = {}
9+
const result = strs.reduce((acc, cur) => {
10+
const charArray = new Array(26).fill(0)
11+
12+
for (let char of cur) {
13+
const charIdx = char.charCodeAt(0) - 'a'.charCodeAt(0)
14+
charArray[charIdx] += 1
15+
}
16+
17+
const sortedValue = charArray.join('#')
18+
19+
const targetIdx = anagramMap[sortedValue]
20+
if (targetIdx !== undefined) {
21+
acc[targetIdx].push(cur)
22+
} else {
23+
anagramMap[sortedValue] = acc.length
24+
acc.push([cur])
25+
}
26+
return acc
27+
}, [])
28+
29+
return result
30+
}

0 commit comments

Comments
ย (0)