[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/python] ํ•ด์‹œ(hash) : ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก

2021. 3. 23. 23:59

๋ฌธ์ œ ์„ค๋ช…

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

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

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

 

์ œํ•œ์‚ฌํ•ญ

  • phone_book์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 1,000,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ๊ฐ ์ „ํ™”๋ฒˆํ˜ธ์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 20 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ๊ฐ™์€ ์ „ํ™”๋ฒˆํ˜ธ๊ฐ€ ์ค‘๋ณตํ•ด์„œ ๋“ค์–ด์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

์ •๋‹ต

def solution(phone_book):
    hash_map = {}
    for i in phone_book:
        hash_map[i] = 1

    for i in phone_book:
        temp = ""
        for number in i:
            temp += number
            if temp in hash_map and temp != i:
                return False
    return True

์ „ํ™”๋ฒˆํ˜ธ๋ฅผ hash_map์— ํ‚ค๋กœ ์ €์žฅํ•œ๋‹ค.

์ „ํ™”๋ฒˆํ˜ธ๋ฅผ ํ•œ๊ธ€์ž์”ฉ ๋Š˜๋ฆฌ๋ฉด์„œ temp์— ์ €์žฅํ•˜๊ณ 

temp๊ฐ’์ด hash_map์— ์žˆ๊ณ  temp๊ฐ’์ด ์ „ํ™”๋ฒˆํ˜ธ ๋งˆ์ง€๋ง‰ ๊ธ€์ž๊นŒ์ง€ ๊ฐ€๊ธฐ ์ „์ด๋ผ๋ฉด False๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด hash_map์— "00"๊ณผ "00232"๊ฐ€ ์žˆ์„ ๋•Œ 

00232๋ฅผ ํ•œ๊ธ€์ž์”ฉ temp์— ์ €์žฅํ•˜๋ฉฐ hash_map๊ณผ ๋น„๊ตํ•œ๋‹ค.

i = 00 ์ผ ๊ฒฝ์šฐ,

temp = 0 ์ผ ๋•Œ, hash_map์— "0"์€ ์—†๋‹ค.

temp = 00 ์ผ ๋•Œ, hash_map์— "00"์ด ์žˆ์ง€๋งŒ i๊ฐ’์ธ 00๊ณผ ๊ฐ™๋‹ค.

i = 00232 ์ผ ๊ฒฝ์šฐ,

temp = 0 ์ผ ๋•Œ, hash_map์— "0"์€ ์—†๋‹ค.

temp = 00 ์ผ ๋•Œ, hash_map์— "00"์ด ์žˆ๊ณ  i๊ฐ’์€ 00232์ด๋ฏ€๋กœ 00๊ณผ ๊ฐ™์ง€์•Š๋‹ค.

๋”ฐ๋ผ์„œ ์ด ๊ฒฝ์šฐ False๋ฅผ returnํ•œ๋‹ค.

 

๋ชจ๋“  ์ „ํ™”๋ฒˆํ˜ธ๋ฅผ ํ™•์ธํ–ˆ์Œ์—๋„ return์ด ์•ˆ๋๋‹ค๋ฉด ์ ‘๋‘์–ด์ธ ๊ฒฝ์šฐ๊ฐ€ ์—†๋‹ค๋Š” ๋œป์ด๋ฏ€๋กœ True๋ฅผ returnํ•œ๋‹ค.

728x90

BELATED ARTICLES

more