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

โฌ› [Programmers] [Python] [2018 KAKAO BLIND RECRUITMENT] [Level2] [3์ฐจ] ์••์ถ•

Dbswnstjd 2023. 4. 14. 12:12

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/17684/solution_groups?language=python3 

 

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

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

programmers.co.kr

 

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 2๋‹จ๊ณ„ - ์••์ถ•
def solution(msg):
    answer = []
    d = {chr(65+i) : i+1 for i in range(26)}
    w, c = 0, 0
    
    while True:
        c += 1
        if c == len(msg):
            answer.append(d[msg[w:c]])
            break
        if msg[w:c+1] not in d:
            d[msg[w:c+1]] = len(d) + 1
            answer.append(d[msg[w:c]])
            w = c
    return answer

์•ŒํŒŒ๋ฒณ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ณ  

w๋Š” ์‹œ์ž‘ ๋ฌธ์ž์—ด, c๋Š” ์ž๋ฅด๋Š” ๋ ๋ฌธ์ž์—ด์ด๋‹ค.

๋งŒ์•ฝ ์ž๋ฅด๋Š” ๋ ๋ฌธ์ž์—ด์ด msg์˜ ๊ธธ์ด์™€ ๊ฐ™๋‹ค๋ฉด ๋งˆ์ง€๋ง‰ ํƒ์ƒ‰์„ ๋งˆ์นœ๊ฒƒ์ด๋ฏ€๋กœ ์ข…๋ฃŒํ•ด์ค€๋‹ค.

๊ทธ๋ฆฌ๊ณ  w๋ถ€ํ„ฐ c+1๊นŒ์ง€ ๋ฌธ์ž์—ด์ด d์— ์—†๋‹ค๋ฉด d[์ž๋ฅธ๋ฌธ์ž์—ด] ์„ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•ด์ฃผ๋„๋ก ํ•˜๊ณ 

์ž๋ฅด๊ธฐ ๋ฐ”๋กœ์ „ ๋ฌธ์ž์—ด์„ answer์— append ํ•ด์ค€๋‹ค. ๋งˆ์ง€๋ง‰์œผ๋กœ ๋‹ค์Œ์ธ๋ฑ์Šค๋กœ ๋„˜์–ด๊ฐ€๊ธฐ ์œ„ํ•ด w = c