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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / PythonํŒŒ์ด์ฌ] ํŠœํ”Œ

meeeeejin 2021. 5. 15. 11:00

๋ฌธ์ œ ๋งํฌ: https://programmers.co.kr/learn/courses/30/lessons/64065

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํŠœํ”Œ

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

ํŠœํ”Œ (a1, a2, a3, a4)๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ์ง‘ํ•ฉ์„ ์›์†Œ์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ž‘์€ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•˜๋ฉด {{a1}, {a1, a2}, {a1, a2, a3}, {a1, a2, a3, a4}}๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. ์ด๋•Œ ์ง‘ํ•ฉ์—์„œ ํŠœํ”Œ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€, {ai} = s[i] - s[i - 1] ์ž…๋‹ˆ๋‹ค. (ํŽธ์˜์ƒ ์ธ๋ฑ์Šค๋ฅผ 1๋ถ€ํ„ฐ ์นด์šดํŠธํ–ˆ์Šต๋‹ˆ๋‹ค. ) ์˜ˆ๋ฅผ ๋“ค์–ด i๋Š” 3์ผ ๋•Œ, s[3] - s[2] = {a1, a2, a3} - {a1, a2} = {a3}์ž…๋‹ˆ๋‹ค. 

 

๋”ฐ๋ผ์„œ ์ฃผ์–ด์ง„ s์˜ ์›์†Œ๋“ค์„ ๋ฆฌ์ŠคํŠธ์— ๋‹ด์•„์„œ ์›์†Œ(์ง‘ํ•ฉ)์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ž‘์€ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค. {ai} = s[i] - s[i - 1]์„ ์ด์šฉํ•ด์„œ ํŠœํ”Œ์˜ ์›์†Œ๋ฅผ ์•ž์—์„œ๋ถ€ํ„ฐ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. 

๋ฌธ์ž์—ด ํ˜•ํƒœ๋ฅผ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด์„œ ast.literal_eval()์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

 

 

 

์†Œ์Šค์ฝ”๋“œ

import ast

def solution(s):
    answer = []
    s = "[" + s[1:-1] + "]"
    s = ast.literal_eval(s)         # s์˜ ์›์†Œ๋“ค์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์ €์žฅ
    s.sort(key=lambda x: len(x))    # ์›์†Œ์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ž‘์€ ์ˆœ์„œ๋Œ€๋กœ s ์ •๋ ฌ
    
    answer.append(list(s[0])[0])
    for i in range(0, len(s) - 1):
        answer.append(list(s[i + 1] - s[i])[0])

    return answer

 

 

 

728x90