Data Structure & Algorithm

[์•Œ๊ณ ๋ฆฌ์ฆ˜-JS] ํ•ด์‹œ (hash) - ์•„๋‚˜๊ทธ๋žจ (Anagram)

fnow 2022. 5. 4. 09:31
๋ฐ˜์‘ํ˜•
๐Ÿ’ก ์•„๋‚˜๊ทธ๋žจ์ด๋ž€, ๋‘ ๋ฌธ์ž์—ด์˜ ๋‚˜์—ด ์ˆœ์„œ๋Š” ๋‹ค๋ฅด์ง€๋งŒ ๊ตฌ์„ฑ์ด ์ผ์น˜ํ•œ ๊ฒƒ์„ ๋งํ•œ๋‹ค.

 

๋ฌธ์ œ

๋‘ ๋ฌธ์ž์—ด์ด ์•„๋‚˜๊ทธ๋žจ์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. 

๋Œ€์†Œ๋ฌธ์ž๋Š” ๊ตฌ๋ถ„๋ฉ๋‹ˆ๋‹ค.

 

์ž…๋ ฅ ์˜ˆ์ œ 1

ABcdefc

BAcdfce

 

์ถœ๋ ฅ ์˜ˆ์ œ 1

YES

 

 

 

 

ํ’€์ด

function solution(a, b) {
  let answer = "YES";
  let hash1 = new Map();
  
  for (let x of a) {
    // ์ด๋ฏธ ์กด์žฌํ•˜๋ฉด
    if (hash1.has(x)) hash1.set(x, hash1.get(x) + 1);
    // ์—†์œผ๋ฉด
    else hash1.set(x, 1);
  }
  
  // ๋‘ ๋ฒˆ์งธ ๋ฌธ์ž์—ด์„ ์ˆœํ™˜ํ•˜๋ฉด์„œ hash1์— ์žˆ์œผ๋ฉด -1
  // hash1์— ํ•ด๋‹น ๊ฐ’์ด ์—†๊ฑฐ๋‚˜ value๊ฐ€ 0์ด๋ฉด ์•„๋‚˜๊ทธ๋žจ ์•„๋‹˜
  for (let x of b) {
    if (!hash1.has(x) || hash1.get(x) === 0) return "NO";
    hash1.set(x, hash1.get(x) - 1);
  }
  
  return answer;
}

 

 

๋ฐ˜์‘ํ˜•