Skip to content

Commit 1fe7d80

Browse files
committed
valid anagram ํ’€์ด
1 parent 53ce7c7 commit 1fe7d80

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} t
4+
* @return {boolean}
5+
*/
6+
var isAnagram = function (s, t) {
7+
const mapS = new Map();
8+
const mapT = new Map();
9+
10+
[...s].map((item) => {
11+
if (mapS.has(item)) {
12+
const itemCount = mapS.get(item);
13+
mapS.set(item, itemCount + 1);
14+
} else {
15+
mapS.set(item, 1);
16+
}
17+
});
18+
19+
[...t].map((item) => {
20+
if (mapT.has(item)) {
21+
const itemCount = mapT.get(item);
22+
mapT.set(item, itemCount + 1);
23+
} else {
24+
mapT.set(item, 1);
25+
}
26+
});
27+
28+
// NOTE - t๊ฐ€ s์˜ anagram์ด๋ผ๋Š” ๋œป์„ ๊ฐฏ์ˆ˜๊ฐ€ ๊ฐ™์ง€์•Š์•„๋„ ๋œ๋‹ค๊ณ  ์ดํ•ดํ–ˆ์œผ๋‚˜ anagram์ •์˜๋Š” s๊ตฌ์„ฑ์›์„ ๋ชจ์ž๋žŒ,๋‚จ๊น€์—†์ด t๋ฅผ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ƒํƒœ
29+
if (mapS.size !== mapT.size) {
30+
return false;
31+
}
32+
33+
for (const [key, value] of mapS) {
34+
if (mapT.get(key) !== value) {
35+
return false;
36+
}
37+
}
38+
39+
return true;
40+
};
41+
42+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
43+
// - ๋ฌธ์ž์—ด s์™€ t๋ฅผ ๊ฐ๊ฐ ํ•œ ๋ฒˆ์”ฉ ์ˆœํšŒ: O(n) + O(n) = O(2n) = O(n)
44+
// - Map ๋น„๊ต๋ฅผ ์œ„ํ•œ ์ˆœํšŒ: O(k), ์—ฌ๊ธฐ์„œ k๋Š” ๊ณ ์œ  ๋ฌธ์ž ๊ฐœ์ˆ˜
45+
// - ๋”ฐ๋ผ์„œ ์ „์ฒด ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(n)
46+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
47+
// - ๋‘ ๊ฐœ์˜ Map ๊ฐ์ฒด ์ƒ์„ฑ: mapS์™€ mapT
48+
// - ๊ฐ Map์€ ์ตœ๋Œ€ k๊ฐœ์˜ ๊ณ ์œ  ๋ฌธ์ž๋ฅผ ์ €์žฅ (k๋Š” ๊ณ ์œ  ๋ฌธ์ž ๊ฐœ์ˆ˜)
49+
// - ์†Œ๋ฌธ์ž ์˜๋ฌธ์ž๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ k โ‰ค 26 (a-z)
50+
// - ๋”ฐ๋ผ์„œ ์ „์ฒด ๊ณต๊ฐ„๋ณต์žก๋„๋Š” O(1) (์ƒ์ˆ˜ ์‹œ๊ฐ„)
51+
52+
// follow up: ์œ ๋‹ˆ์ฝ”๋“œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค. ํฐ ์˜๋ฏธ๋Š” ์—†์Œ
53+
console.log(isAnagram("๐Ÿ˜€๐Ÿ˜€", "๐Ÿ˜€๐Ÿ˜€๐Ÿ˜€"));
54+
// false
55+
console.log(isAnagram("ํ•œ๊ธ€๊ธ€", "๊ธ€ํ•œ๊ธ€"));
56+
// true
57+
console.log(isAnagram("cafรฉ", "รฉfac"));
58+
// true
59+
console.log(isAnagram("Helloไธ–็•Œ", "ไธ–็•ŒHello"));
60+
// true
61+
console.log(isAnagram("์•ˆ๋…• ํ•˜์„ธ์š”", "ํ•˜์„ธ์š” ์•ˆ๋…•"));
62+
// true
63+
console.log(isAnagram("Cafรฉ", "รฉfac"));
64+
// false
65+
console.log(isAnagram("Cafรฉ", "ร‰fac"));
66+
// false

0 commit comments

Comments
ย (0)