๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[์ธํ๋ฐ ์น์
5] ์๋๊ทธ๋จ (Javascript)
์ ๋ฃ ๊ฐ์์ธ ๊ด๊ณ๋ก ๋ฌธ์ ์ค๋ช
์ ์๋ตํฉ๋๋ค.
โ๏ธIdea Sketch
2021-06-25
1. ๋ฌธ์์ด ๋๋ค hash ์ ํ
- hash1[str1[i]] ๊ฐ์ด ์์ผ๋ฉด hash1[str1[i]] + 1
- hash1[str1[i]] ๊ฐ์ด ์์ผ๋ฉด 0 + 1
let hash1 = new Map();
let hash2 = new Map();
for (let i=0; i<str1.length; i++) {
hash1.set(str1[i], (hash1.get(str1[i]) || 0) + 1);
hash2.set(str2[i], (hash2.get(str2[i]) || 0) + 1);
}
์ฃผ์
hashstr[i]
2. hash1 === hash2 ๊ฒฐ๊ณผ๋?
- key-value ์์ ๊ตฌ์ฑ๊ณผ ๋ฐฐ์ด์์๊ฐ ์ผ์นํด๋ false ๋ฐํ
console.log(hash1); // output: Map { 'A' => 1, 'b' => 1, 'a' => 1, 'e' => 1, 'C' => 1 }
console.log(hash2); // output: Map { 'A' => 1, 'b' => 1, 'a' => 1, 'e' => 1, 'C' => 1 }
console.log(hash1 === hash2); // output: false
console.log(hash1 === hash1); // output: true
3. hash.size ์ผ์น์ฌ๋ถ ํ์ธ
if (hash1.size !== hash2.size) return "NO";
์ฃผ์
hash.size() (O)
hash.size (X)
ํท๊ฐ๋ฆด ๋ arr.length๋ฅผ ๋ ์ฌ๋ฆฌ์
4. for (let [key, val] of hash)๋ก key-value์์ด ์ผ์นํ๋์ง ํ์ธ
for (let [key, val] of hash1) {
if (val !== hash2.get(key)) return "NO";
}
5. 3๋ฒ๊ณผ 4๋ฒ์ ํต๊ณผํ๋ฉด return "YES";
โ๏ธ์์ค์ฝ๋
2021-06-25
function solution(str1, str2) {
let hash1 = new Map();
let hash2 = new Map();
for (let i = 0; i < str1.length; i++) {
hash1.set(str1[i], (hash1.get(str1[i]) || 0) + 1);
hash2.set(str2[i], (hash2.get(str2[i]) || 0) + 1);
}
if (hash1.size !== hash2.size) return "NO";
for (let [key, val] of hash1) {
if (val !== hash2.get(key)) return "NO";
}
return "YES";
}