์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜5] ์•„๋‚˜๊ทธ๋žจ (Javascript)

์€์ง„ 2021. 6. 25. 21:07

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜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";
}