Skip to content

Commit 1008b49

Browse files
committed
Valid Anagram solution
1 parent dc2264d commit 1008b49

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

โ€Žvalid-anagram/jdy8739.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const getDictionary = (s) => {
2+
const arr = s.split('');
3+
4+
const dict = {};
5+
6+
for (let i=0; i<arr.length; i++) {
7+
const key = arr[i];
8+
const value = dict[key];
9+
10+
if (value === undefined) {
11+
dict[key] = 1;
12+
} else {
13+
dict[key] = dict[key] + 1;
14+
}
15+
}
16+
17+
return dict;
18+
}
19+
20+
const checkSameLength = (dictA, dictB) => {
21+
return Object.keys(dictA).length === Object.keys(dictB).length
22+
}
23+
24+
const checkSameDict = (s, t) => {
25+
for (const key in s) {
26+
if (s[key] !== t[key]) {
27+
return false;
28+
}
29+
}
30+
31+
return true;
32+
}
33+
34+
/**
35+
* @param {string} s
36+
* @param {string} t
37+
* @return {boolean}
38+
*/
39+
var isAnagram = function(s, t) {
40+
const dictA = getDictionary(s);
41+
42+
const dictB = getDictionary(t);
43+
44+
return checkSameLength(dictA, dictB) && checkSameDict(dictA, dictB);
45+
};
46+
47+
// ๊ณต๊ฐ„๋ณต์žก๋„: ํ•ด์‹œ ํ…Œ์ด๋ธ”์— ๋ชจ๋“  ๋ฌธ์ž๋ฅผ ์ €์žฅํ•˜๊ฒŒ ๋˜๋ฏ€๋กœ O(n)
48+
// ์‹œ๊ฐ„๋ณต์žก๋„: ๋‘ ๊ฐœ์˜ ๋ฌธ์ž์—ด์„ ํ•œ ๋ฒˆ์”ฉ ๋ฃจํ”„๋ฅผ ๋Œ๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— 0(n)
49+

0 commit comments

Comments
ย (0)