๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section05 - 7 - ์•„๋‚˜๊ทธ๋žจ

by YWTechIT 2021. 8. 29.
728x90

๐Ÿ“ section05 - 7 - ์•„๋‚˜๊ทธ๋žจ

Anagram์€ ๋‘ ๋ฌธ์ž์—ด์ด ์•ŒํŒŒ๋ฒณ์˜ ๋‚˜์—ด ์ˆœ์„œ๋ฅผ ๋‹ค๋ฅด์ง€๋งŒ ๊ทธ ๊ตฌ์„ฑ์ด ์ผ์น˜ํ•˜๋ฉด ๋‘ ๋‹จ์–ด๋ฅผ ์•„๋‚˜๊ทธ๋žจ์ด๋ผ๊ณ  ํ•œ๋‹ค. ์ด ๋ฌธ์ œ๋ฅผ hash๋กœ ํ’€๋ฉด O(N)์œผ๋กœ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์•„๋‚˜๊ทธ๋žจ์ด ์„ฑ๋ฆฝํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐํ•˜๋ฉด ํŽธํ•˜๋‹ค.

 

  1. ๋ฌธ์ž์—ด s1์˜ ์›์†Œ๋ฅผ hash๊ฐ’์œผ๋กœ ๋งŒ๋“ ๋‹ค.
  2. ๋น„๊ตํ•  ๋ฌธ์ž์—ด s2๋ฅผ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ˆœํšŒํ•˜๋ฉด์„œ ์•„๋‚˜๊ทธ๋žจ์ด ๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ๋Š”๋‹ค.(์•„๋‚˜๊ทธ๋žจ์ด ์„ฑ๋ฆฝํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ: s2์˜ ๊ฐ’์ด hash๊ฐ’์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ, hash๊ฐ’์˜ value๊ฐ€ 1๋ณด๋‹ค ์ž‘์€๊ฒฝ์šฐ)
  3. ์กฐ๊ฑด๋ฌธ๋ฐ–์—๋Š” hash์˜ key๊ฐ’์„ -1์”ฉ ๋นผ์ค€๋‹ค.

 

728x90

 

let s1 = "AbaAeCe";
let s2 = "baeeACA";
let s1H = new Map();

console.log(solution(s1, s2));

function solution(s1, s2) {
  for (let x of s1) {
    if (s1H.has(x)) s1H.set(x, s1H.get(x) + 1);
    else s1H.set(x, 1);
  }

  console.log(s1H)

  for (let x of s2) {
    if (!s1H.has(x) | (s1H.get(x) < 1)) return "NO";
    s1H.set(x, s1H.get(x) - 1);
    console.log(x, s1H)
  }
  return "YES";
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€