Algorithms/Programmers

ํ•ด์‹œ lv2. ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก (๋ฆฌ์ŠคํŠธ vs ํ•ด์‹œ)

ํƒฑ์ ค 2021. 2. 25. 01:50

์ถœ์ฒ˜: ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ์—ฐ์Šต, https://programmers.co.kr/learn/challenges

 

๋ฌธ์ œ ์„ค๋ช…

์ „ํ™”๋ฒˆํ˜ธ๋ถ€์— ์ ํžŒ ์ „ํ™”๋ฒˆํ˜ธ ์ค‘, ํ•œ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ค๋ฅธ ๋ฒˆํ˜ธ์˜ ์ ‘๋‘์–ด์ธ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค.
์ „ํ™”๋ฒˆํ˜ธ๊ฐ€ ๋‹ค์Œ๊ณผ ๊ฐ™์„ ๊ฒฝ์šฐ, ๊ตฌ์กฐ๋Œ€ ์ „ํ™”๋ฒˆํ˜ธ๋Š” ์˜์„์ด์˜ ์ „ํ™”๋ฒˆํ˜ธ์˜ ์ ‘๋‘์‚ฌ์ž…๋‹ˆ๋‹ค.

  • ๊ตฌ์กฐ๋Œ€ : 119
  • ๋ฐ•์ค€์˜ : 97 674 223
  • ์ง€์˜์„ : 11 9552 4421

์ „ํ™”๋ฒˆํ˜ธ๋ถ€์— ์ ํžŒ ์ „ํ™”๋ฒˆํ˜ธ๋ฅผ ๋‹ด์€ ๋ฐฐ์—ด phone_book ์ด solution ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์–ด๋–ค ๋ฒˆํ˜ธ๊ฐ€ ๋‹ค๋ฅธ ๋ฒˆํ˜ธ์˜ ์ ‘๋‘์–ด์ธ ๊ฒฝ์šฐ๊ฐ€ ์žˆ์œผ๋ฉด false๋ฅผ ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด true๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ ์‚ฌํ•ญ

  • phone_book์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 1,000,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ๊ฐ ์ „ํ™”๋ฒˆํ˜ธ์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 20 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ์ œ

phone_book, return

[119, 97674223, 1195524421] false
[123,456,789] true
[12,123,1235,567,88] false

 

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์ž…์ถœ๋ ฅ ์˜ˆ #1
์•ž์—์„œ ์„ค๋ช…ํ•œ ์˜ˆ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ #2
ํ•œ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ค๋ฅธ ๋ฒˆํ˜ธ์˜ ์ ‘๋‘์‚ฌ์ธ ๊ฒฝ์šฐ๊ฐ€ ์—†์œผ๋ฏ€๋กœ, ๋‹ต์€ true์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ #3
์ฒซ ๋ฒˆ์งธ ์ „ํ™”๋ฒˆํ˜ธ, “12”๊ฐ€ ๋‘ ๋ฒˆ์งธ ์ „ํ™”๋ฒˆํ˜ธ “123”์˜ ์ ‘๋‘์‚ฌ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋‹ต์€ false์ž…๋‹ˆ๋‹ค.

# ํ•ด์‰ฌ ๊ตฌํ˜„
def solution(phone_book):
    answer = True
    hash_map = {}
    
    for i in phone_book:
        hash_map[i] = 1
    
    for i in phone_book:
        chk = ""
        for j in i:
            chk += j
            if chk in hash_map and chk != i:
                answer = False        
    return answer

# collections ์ด์šฉํ•œ ํ•ด์‰ฌ ๊ตฌํ˜„
import collections
def solution(phone_book):
    answer = True
    hash_book = collections.Counter(phone_book)
    for i in phone_book:
        chk = ""
        for j in i:
            chk += j
            if chk in hash_book and chk != i:
                answer = False
    return answer

# ๊ฐ™์€ ์•„์ด๋””์–ด๋กœ ํ•ด์‰ฌ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  list๋ฅผ ์‚ฌ์šฉํ•ด ๋ดค์œผ๋‚˜ ํšจ์œจ์„ฑ์—์„œ ๋ฌธ์ œ
# list๋Š” ์„ ํ˜• ํƒ์ƒ‰ O(N), ํ•ด์‰ฌ๋Š” ๋”•์…”๋„ˆ๋ฆฌ ์ž๋ฃŒํ˜•์œผ๋กœ O(1)
def solution(phone_book):
    answer = True
    for i in phone_book:
        chk = ""
        for j in i:
            chk += j
            if chk in phone_book and chk != i:
                answer = False
    return answer

# zip์œผ๋กœ phonebook, phoneBook[1:] ๋ฌถ์–ด์„œ ์•ž๋’ค๊ฐ’ ๋น„๊ต
# ๊ฒน์น˜์ง€ ์•Š๋Š” p2๊ฐ€ p1์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š”์ง€ ํ™•์ธ
def solution(phoneBook):
    phoneBook = sorted(phoneBook)
    print(zip(phoneBook, phoneBook[1:]))
    for p1, p2 in zip(phoneBook, phoneBook[1:]):
        if p2.startswith(p1):
            return False
    return True

 

๋ฆฌ์ŠคํŠธ๋Š” ์„ ํ˜• ํƒ์ƒ‰์œผ๋กœ O(N)์˜ ์‹œ๊ฐ„ →ํ•ด์‹œ ๋”•์…”๋„ˆ๋ฆฌ ์ž๋ฃŒํ˜•์œผ๋กœ O(1)๋กœ ๊ฐœ์„ ํ•˜๊ธฐ

 

728x90