๋ณธ๋ฌธ์œผ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

42577. ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
ํ•ด์‹œlv.130๋ถ„โœ…

์„ค๊ณ„ ๋ฐฉ๋ฒ•#

  • ํ•ด์‹œ๋กœ ํ’€์ดํ•˜๋Š” ๋ฒ•์ด ๋– ์˜ค๋ฅด์ง€ ์•Š์•˜์Œ.

  • phone_book์„ ๋จผ์ € ์ •๋ ฌํ•จ.

    • ['119', '97674223', '1195524421'] -> ['119', '1195524421', '97674223'] ๋กœ์ •๋ ฌ๋จ.
  • sort๋œ ๋ฐฐ์—ด์„ reduce๋กœ ์ˆœํšŒํ•˜๋ฉฐ ํ˜„์žฌ ๊ฐ’์ด ๊ทธ ์ด์ „ ๊ฐ’์œผ๋กœ startsWith ํ•˜๋Š”์ง€ ํŒ๋‹จํ•จ.

  • startsWith ์ด true ๋ผ๋ฉด answer๋ฅผ false๋กœ ๋ฐ”๊พธ๊ณ  reduce๋ฅผ early break ํ•จ.

์ฝ”๋“œ#

JavaScript#

function solution(phone_book) {    let answer = true;
    phone_book        .sort()        .slice(0)        .reduce((short, long, _, arr) => {            if (long.startsWith(short)) {                answer = false;                arr.splice(1);            }            return long;        });
    return answer;}

Python#

def solution(phone_book):    phone_book = sorted(phone_book)
    for short, long in zip(phone_book, phone_book[1:]):        if long.startswith(short):            return False    return True

์‹œ๊ฐ„ ๋ณต์žก๋„#

sort() : O(NlogN) reduce : O(N)

O(NlogN) + O(N) ๋งž๋‚˜..?

์–ด๋ ค์› ๋˜ ์ #

  • ํ•ด์‹œ๋กœ ๋ถ„๋ฅ˜๋˜์–ด ์žˆ์–ด์„œ ์ƒ๊ฐ์ด ํ•ด์‹œ๋กœ ๊ณ ์ •๋˜์—ˆ๋Š”๋ฐ, ํ•ด์‹œ๋กœ ํ‘ธ๋Š” ๋ฐฉ๋ฒ•์ด ์‰ฝ๊ฒŒ ์•ˆ๋– ์˜ฌ๋ž์Œ.

  • ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์—์„œ JS๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š๋Š” ๋ฌธ์ œ๋ผ, ํŒŒ์ด์ฌ์œผ๋กœ ๋จผ์ € ํ’€์—ˆ์–ด์•ผ ํ–ˆ์Œ.

์ฐธ๊ณ ์ž๋ฃŒ#