์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์กฐ์ด์Šคํ‹ฑ (Greedy)

ghtis1798 2021. 6. 21. 19:29

 

 

๐Ÿ”ธ ๋ฌธ์ œ์ ‘๊ทผ๋ฐฉ์‹

  1. 'A' ๋ฌธ์ž๊ฐ€ ์•„๋‹Œ ๊ณณ์œผ๋กœ ์ด๋™ํ•˜๊ธฐ๊นŒ์ง€ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ์ด๋™ ํšŸ์ˆ˜๋ฅผ ๊ณ„์‚ฐ ํ›„ ์ตœ์†Œ๊ฐ’์„ ๋”ํ•œ๋‹ค.
  2. ์™ผ์ชฝ or ์˜ค๋ฅธ์ชฝ ์ด๋™ ํ›„, ๋ฌธ์ž ์™„์„ฑ์„ ์œ„ํ•ด 'A'์—์„œ๋ถ€ํ„ฐ ๋ฌธ์ž๊นŒ์ง€, 'Z'์—์„œ๋ถ€ํ„ฐ ๋ฌธ์ž๊นŒ์ง€ ํšŸ์ˆ˜๋ฅผ ๊ณ„์‚ฐ ํ›„ ์ตœ์†Ÿ๊ฐ’์„ ๋”ํ•œ๋‹ค.
  3. ๋ชจ๋“  ์œ„์น˜๋ฅผ ๋‹ค ๋ฐฉ๋ฌธํ•˜์—ฌ ๋ฌธ์ž์—ด์„ ์™„์„ฑ ์‹œ ์ข…๋ฃŒํ•œ๋‹ค.
    • ํŒŒ์ด์ฌ์—์„œ ๋ฆฌ์ŠคํŠธ๋Š” ์Œ์ˆ˜๋กœ๋„ indexing์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
    • ๊ฐ€์šด๋ฐ ์ค‘๊ฐ„ ์ง€์ ์—์„œ๋ถ€ํ„ฐ ๊ณ„์‚ฐํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ์ฃผ์–ด์ง„ ์กฐ๊ฑด 'A'๋ถ€ํ„ฐ ํ˜น์€ ๋’ค์—์„œ 'Z'๋ถ€ํ„ฐ ๊ณ„์‚ฐํ•  ๊ฒƒ

๐Ÿ’ง Source Code

def solution(name):
    ''' Programmers ์กฐ์ด์Šคํ‹ฑ ๋ฌธ์ œํ’€์ด - Greedy

    Notes:
        1. 'A' ๋ฌธ์ž๊ฐ€ ์•„๋‹Œ ๊ณณ์œผ๋กœ ์ด๋™ํ•˜๊ธฐ๊นŒ์ง€ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ์ด๋™ ํšŸ์ˆ˜๋ฅผ ๊ณ„์‚ฐ ํ›„ ์ตœ์†Œ๊ฐ’์„ ๋”ํ•œ๋‹ค.
        2. ์™ผ์ชฝ or ์˜ค๋ฅธ์ชฝ ์ด๋™ ํ›„, ๋ฌธ์ž ์™„์„ฑ์„ ์œ„ํ•ด 'A'์—์„œ๋ถ€ํ„ฐ ๋ฌธ์ž๊นŒ์ง€, 'Z'์—์„œ๋ถ€ํ„ฐ ๋ฌธ์ž๊นŒ์ง€ ํšŸ์ˆ˜๋ฅผ ๊ณ„์‚ฐ ํ›„ ์ตœ์†Ÿ๊ฐ’์„ ๋”ํ•œ๋‹ค.
        3. ๋ชจ๋“  ์œ„์น˜๋ฅผ ๋‹ค ๋ฐฉ๋ฌธํ•˜์—ฌ ๋ฌธ์ž์—ด์„ ์™„์„ฑ ์‹œ ์ข…๋ฃŒํ•œ๋‹ค.
        - ํŒŒ์ด์ฌ์—์„œ ๋ฆฌ์ŠคํŠธ๋Š” ์Œ์ˆ˜๋กœ๋„ indexing์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
        - ๊ฐ€์šด๋ฐ ์ค‘๊ฐ„ ์ง€์ ์—์„œ๋ถ€ํ„ฐ ๊ณ„์‚ฐํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ์ฃผ์–ด์ง„ ์กฐ๊ฑด 'A'๋ถ€ํ„ฐ ํ˜น์€ ๋’ค์—์„œ 'Z'๋ถ€ํ„ฐ ๊ณ„์‚ฐํ•  ๊ฒƒ

    Args:
        name (str) : ์™„์„ฑํ•  ๋ฌธ์ž์—ด

    Returns:
        answer (int) : ์กฐ์ด์Šคํ‹ฑ ์ด๋™ํšŸ์ˆ˜

    '''

    idx, answer = 0
    name_cnt = [min(ord(i)-ord('A'), 1+ord('Z')-ord(i))  for i in name]

    while True:
        answer += name_cnt[idx]
        name_cnt[idx] = 0
        left, right = 1,1

        if sum(name_cnt) == 0:
            break

        if name_cnt[idx] == 0:
            while name_cnt[idx-left] != 0:
                left += 1
            while name_cnt[idx+right] != 0:
                right += 1

        answer += left if left < right else left
        idx += -left if left < right else right

    return answer

 

์ฐธ๊ณ ํ•œ ๋ธ”๋กœ๊ทธ