๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Python] [Level2] ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก

Dbswnstjd 2023. 4. 11. 17:45

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/42577

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 2๋‹จ๊ณ„ - ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก
def solution(phone_book):
    hash_map = {}
    for phone_number in phone_book:
        hash_map[phone_number] = 1
    
    for phone_number in phone_book:
        s = ""
        for number in phone_number:
            s += number
            if s in hash_map and s != phone_number:
                return False
    return True
print(solution(["123","456","789"]))

์ด๋ฒˆ ๋ฌธ์ œ๋Š” Hash Map ์„ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค. HashTable์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(1)์œผ๋กœ ํƒ์ƒ‰ ์‹œ๊ฐ„์ด 1์ด๋‹ค. 

phone_book์˜ ๊ธธ์ด๊ฐ€ 100๋งŒ์ธ ๋งŒํผ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ƒ๊ฐํ•ด์„œ ํ’€์–ดํ– ํ–ˆ๋˜ ๋ฌธ์ œ์˜€๋‹ค.