[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์กฐ์ด์Šคํ‹ฑ /ํŒŒ์ด์ฌ /Python /ํƒ์š•๋ฒ•(Greedy)
Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์กฐ์ด์Šคํ‹ฑ /ํŒŒ์ด์ฌ /Python /ํƒ์š•๋ฒ•(Greedy)

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ’กsolutions )

๐Ÿ’ฌ ๋กœ์ง ํฌ๊ฒŒ ๋‘ ๊ฐ€์ง€ => ์ƒํ•˜๋กœ ์ตœ์†Œ ๊ฑฐ๋ฆฌ ๊ตฌํ•ด์„œ ์•ŒํŒŒ๋ฒณ ๋ฐ”๊พธ๊ธฐ / ์ขŒ์šฐ๋กœ ์ตœ์†Œ ๊ฑฐ๋ฆฌ ๊ตฌํ•ด์„œ ๋ฐฉํ–ฅ ์ •ํ•œ ํ›„ ์ด๋™ํ•˜๊ธฐ 

๐Ÿ’ฌ change ๋ฐฐ์—ด์—๋Š” ๊ฐ ์•ŒํŒŒ๋ฒณ๋งˆ๋‹ค ์ƒํ•˜ ์กฐ์ • ์ค‘ min๊ฐ’์œผ๋กœ ์ตœ์†Œ ํšŸ์ˆ˜๋ฅผ ๋‹ด์•„๋‘๊ธฐ

๐Ÿ’ฌ idx 0๋ฒˆ ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์ขŒ์šฐ ์ด๋™ ํšŸ์ˆ˜๋ฅผ answer์— ๋”ํ•ด์ฃผ๊ธฐ

๐Ÿ’ฌ ์ขŒ์šฐ ๋ฐฉํ–ฅ ์ „ํ™˜ ์‹œ์—๋Š” ๋ฐ”๊ฟ”์•ผํ•˜๋Š” ์•ŒํŒŒ๋ฒณ์ด ๋‚˜์˜ค๊ธฐ๊นŒ์ง€์˜ ์ขŒ์šฐ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๊ณ , ๊ทธ ์ค‘ ์ตœ์†Œ๊ฐ’์ด ๋˜๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์ „ํ™˜ํ•œ๋‹ค.

๐Ÿ’ฌ ๋ชจ๋“  ์•ŒํŒŒ๋ฒณ์ด ์กฐ์ •๋œ ๊ฒฝ์šฐ(change์˜ sum์ด 0์ผ ๋•Œ) -> ๊ฒฐ๊ณผ๊ฐ’ ๋ฐ˜ํ™˜

 

๐ŸŽซcode )

def solution(name):
    # ์ƒํ•˜ ์กฐ์ •์œผ๋กœ ์•ŒํŒŒ๋ฒณ ๋ฐ”๊พธ๊ธฐ 
    change = [min(ord(i) - ord('A'), ord('Z') - ord(i) + 1) for i in name]
    idx = 0
    answer = 0

    while True:
        answer += change[idx]
        change[idx] = 0
        if sum(change) == 0:
            return answer

        # ์ขŒ์šฐ ์ด๋™ํ–ฅ๋ฐฉ์„ ์ •ํ•˜๊ธฐ
        left, right = 1, 1
        while change[idx - left] == 0:
            left += 1
        while change[idx + right] == 0:
            right += 1
        # ์œ„์น˜(์ธ๋ฑ์Šค) ์กฐ์ •
        answer += left if left < right else right
        idx += -left if left < right else right

 

๐Ÿ“Œ description )

๋ฌธ์ œ์ถœ์ฒ˜ : programmers.co.kr/learn/courses/30/lessons/42860?language=python3

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์กฐ์ด์Šคํ‹ฑ

์กฐ์ด์Šคํ‹ฑ์œผ๋กœ ์•ŒํŒŒ๋ฒณ ์ด๋ฆ„์„ ์™„์„ฑํ•˜์„ธ์š”. ๋งจ ์ฒ˜์Œ์—” A๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค. ex) ์™„์„ฑํ•ด์•ผ ํ•˜๋Š” ์ด๋ฆ„์ด ์„ธ ๊ธ€์ž๋ฉด AAA, ๋„ค ๊ธ€์ž๋ฉด AAAA ์กฐ์ด์Šคํ‹ฑ์„ ๊ฐ ๋ฐฉํ–ฅ์œผ๋กœ ์›€์ง์ด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. โ–ฒ - ๋‹ค

programmers.co.kr

 

๋ฌธ์ œ ์„ค๋ช…
์กฐ์ด์Šคํ‹ฑ์œผ๋กœ ์•ŒํŒŒ๋ฒณ ์ด๋ฆ„์„ ์™„์„ฑํ•˜์„ธ์š”. ๋งจ ์ฒ˜์Œ์—” A๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
ex) ์™„์„ฑํ•ด์•ผ ํ•˜๋Š” ์ด๋ฆ„์ด ์„ธ ๊ธ€์ž๋ฉด AAA, ๋„ค ๊ธ€์ž๋ฉด AAAA

์กฐ์ด์Šคํ‹ฑ์„ ๊ฐ ๋ฐฉํ–ฅ์œผ๋กœ ์›€์ง์ด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.
์˜ˆ๋ฅผ ๋“ค์–ด ์•„๋ž˜์˜ ๋ฐฉ๋ฒ•์œผ๋กœ JAZ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋งŒ๋“ค๊ณ ์ž ํ•˜๋Š” ์ด๋ฆ„ name์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ,
์ด๋ฆ„์— ๋Œ€ํ•ด ์กฐ์ด์Šคํ‹ฑ ์กฐ์ž‘ ํšŸ์ˆ˜์˜ ์ตœ์†Ÿ๊ฐ’์„ return ํ•˜๋„๋ก
solution ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ์„ธ์š”.


์ œํ•œ ์‚ฌํ•ญ
name์€ ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
name์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 20 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ


โ€ป ๊ณต์ง€ - 2019๋…„ 2์›” 28์ผ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

๋ฐ˜์‘ํ˜•