Skip to content

Commit cf176d6

Browse files
committed
week2: valid-anagram
1 parent 01f178e commit cf176d6

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

โ€Žvalid-anagram/reeseo3o.jsโ€Ž

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Anagram - ๋‘ย ๋ฌธ์ž์—ด์ดย ๊ฐ™์€ย ์•ŒํŒŒ๋ฒณ์„ย ๊ฐ™์€ย ๊ฐœ์ˆ˜๋งŒํผย ๊ฐ€์ง€๊ณ ย ์žˆ์–ด์•ผ ํ•จ.
2+
3+
// O(n log n) - ์ •๋ ฌ ๋ฐฉ์‹
4+
const isAnagram = (s, t) => {
5+
// 1๋‹จ๊ณ„: ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋ฉด ์ ˆ๋Œ€ anagram ๋ถˆ๊ฐ€ โ†’ ๋ฐ”๋กœ false ๋ฐ˜ํ™˜
6+
if (s.length !== t.length) return false;
7+
8+
// 2๋‹จ๊ณ„: ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ์ชผ๊ฐœ๊ณ  โ†’ ์ •๋ ฌํ•˜๊ณ  โ†’ ๋‹ค์‹œ ๋ฌธ์ž์—ด๋กœ ํ•ฉ์น˜๊ธฐ
9+
const sortedS = s.split('').sort().join('');
10+
const sortedT = t.split('').sort().join('');
11+
12+
// 3๋‹จ๊ณ„: ์ •๋ ฌ๋œ ๋‘ ๋ฌธ์ž์—ด์ด ๊ฐ™์œผ๋ฉด anagram
13+
return sortedS === sortedT;
14+
};
15+
16+
// O(n) - ํ•ด์‹œ๋งต ๋ฐฉ์‹
17+
const isAnagram2 = (s, t) => {
18+
// [์ฃผ์˜] s.length๋Š” ์‹ค์ œ ๋ฌธ์ž ์ˆ˜๊ฐ€ ์•„๋‹Œ UTF-16 ์ฝ”๋“œ ์œ ๋‹› ์ˆ˜๋ฅผ ์…ˆ. - "The number of UTF-16 code units in the string"
19+
// ์ด๋ชจ์ง€ ๊ฐ™์€ ๋ฌธ์ž๋Š” ์ฝ”๋“œ ์œ ๋‹› 2๊ฐœ๋ฅผ ์ฐจ์ง€ํ•ด์„œ ์‹ค์ œ ๋ฌธ์ž ์ˆ˜์™€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์Œ.
20+
// "๐Ÿ˜€".length โ†’ 2 (์ฝ”๋“œ ์œ ๋‹› ๊ธฐ์ค€)
21+
// [..."๐Ÿ˜€"].length โ†’ 1 (์‹ค์ œ ๋ฌธ์ž ๊ธฐ์ค€)
22+
// Unicode ์™„์ „ ๋Œ€์‘์ด ํ•„์š”ํ•˜๋ฉด [...s].length !== [...t].length ๋กœ ์ˆ˜์ •.
23+
// ์ด ๋ฌธ์ œ๋Š” ์†Œ๋ฌธ์ž ์˜์–ด ์•ŒํŒŒ๋ฒณ๋งŒ ๋‹ค๋ฃจ๋ฏ€๋กœ s.length ์‚ฌ์šฉํ•ด๋„ ๋ฌด๋ฐฉ.
24+
if (s.length !== t.length) return false;
25+
26+
const count = {};
27+
28+
// for...of๋Š” ์‹ค์ œ ๋ฌธ์ž ๋‹จ์œ„๋กœ ์ˆœํšŒํ•˜๋ฏ€๋กœ Unicode ์•ˆ์ „.
29+
// count[char]๊ฐ€ ์—†์œผ๋ฉด 0์œผ๋กœ ์ดˆ๊ธฐํ™” ํ›„ +1.
30+
for (const char of s) {
31+
count[char] = (count[char] || 0) + 1;
32+
}
33+
34+
// t์— ์žˆ๋Š” ๋ฌธ์ž๊ฐ€ count์— ์—†๊ฑฐ๋‚˜(0, undefined) โ†’ s์— ์—†๋Š” ๋ฌธ์ž โ†’ false.
35+
for (const char of t) {
36+
if (!count[char]) return false;
37+
count[char]--;
38+
}
39+
40+
// ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ์†Œ์ง„๋˜๋ฉด anagram.
41+
return true;
42+
};

0 commit comments

Comments
ย (0)