๐Ÿ”Žํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก

๋ฐ•๋ฏผ์šฐยท2023๋…„ 7์›” 9์ผ
0
post-custom-banner

๋ฌธ์ œ : https://school.programmers.co.kr/learn/courses/30/lessons/42577

์นดํ…Œ๊ณ ๋ฆฌ : ํ•ด์‹œ

์ถœ์ฒ˜: ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๊ณ ๋“์  Kit, https://school.programmers.co.kr/learn/challenges?tab=algorithm_practice_kit


โœ๏ธ ๋‚ด ํ’€์ด

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์‚ฌ์ดํŠธ์—์„œ๋Š” JS ์–ธ์–ด๋ฅผ ์ง€์›ํ•ด์ฃผ์ง€ ์•Š๋Š” ๋ฌธ์ œ์˜€์ง€๋งŒ ๊ทธ๋ƒฅ JS๋กœ ํ’€์–ด๋ณด์•˜๋‹ค.

๊ฐ ์ „ํ™”๋ฒˆํ˜ธ๋ฅผ map์— ์ €์žฅํ•ด๋†“๊ณ , ํŠน์ • ์ „ํ™”๋ฒˆํ˜ธ์˜ ์ ‘๋‘์–ด๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž์—ด๋“ค์„ ํ•˜๋‚˜์”ฉ ๊ฒ€์‚ฌํ•˜๋ฉด์„œ ๊ฐ ๋ฌธ์ž์—ด์ด map์— ์žˆ๋Š”์ง€๋ฅผ ํ™•์ธํ•  ๊ฒƒ์ด๋‹ค.


ex)

์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก์œผ๋กœ["123", "456", "789"]๊ฐ€ ์ฃผ์–ด์กŒ๋‹ค๋ฉด, map์€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ตฌ์กฐ๋กœ ๋งŒ๋“ค์–ด์งˆ ๊ฒƒ์ด๊ณ 

{
    "123" : 1,
    "456" : 1,
    "789" : 1
}

"123"์˜ ์ ‘๋‘์–ด๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” 1, 12๊ฐ€ map์— ์žˆ๋Š”์ง€ ํ™•์ธํ•  ๊ฒƒ์ด๊ณ , ์ด๋ฅผ ๋‚˜๋จธ์ง€ "456", "789"์— ๋Œ€ํ•ด์„œ๋„ ๋ฐ˜๋ณตํ•  ๊ฒƒ์ด๋‹ค. ํƒ์ƒ‰ํ•˜๋ฉด์„œ ํŠน์ • ์ „ํ™”๋ฒˆํ˜ธ์˜ ์ ‘๋‘์–ด๊ฐ€ map์— ์žˆ๋‹ค๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ๋๊นŒ์ง€ ์—†์—ˆ๋‹ค๋ฉด true๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.


๐Ÿ—’๏ธ ๋‚ด ์ฝ”๋“œ

function solution(phone_book) {
  const table = new Map();
  phone_book.forEach((element) => {
    table.set(element, 1);
  });

  for (let i = 0; i < phone_book.length; i++) {
    for (let j = 1; j < phone_book[i].length; j++) {
      if (table.get(phone_book[i].substring(0, j))) {
        return false;
      }
    }
  }

  return true;
}

console.log(solution(["123", "456", "789"])); // true
console.log(solution(["119", "97674223", "1195524421"])); // 	false

๐Ÿ“Œ ์•Œ๊ฒŒ๋œ ์ 

ํŠน์ • ์ ‘๋‘์–ด๊ฐ€ ์กด์žฌํ•˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•  ๋•Œ map์„ ์‚ฌ์šฉํ•œ ๊ฒƒ์ฒ˜๋Ÿผ, ์ˆœ์„œ์™€ ์ƒ๊ด€ ์—†์ด ํŠน์ • ๊ฐ’์˜ ์กด์žฌ ์—ฌ๋ถ€๋งŒ์„ ๋น ๋ฅด๊ฒŒ ํŒ๋‹จํ•  ๋•Œ map์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ์ข‹๋‹ค๊ณ  ๋Š๊ผˆ๋‹ค. map ์ž๋ฃŒ๊ตฌ์กฐ๋Š” key๊ฐ’์„ ํ†ตํ•ด O(1)์— value ๊ฐ’์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

profile
๊พธ์ค€ํžˆ, ๊นŠ๊ฒŒ
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€