์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํฐ ์ˆ˜ ๋งŒ๋“ค๊ธฐ(Greedy)

ghtis1798 2021. 6. 22. 19:43

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

  1. stack์— ๊ฐ’์ด ์—†๊ฑฐ๋‚˜, ๋” ์ž‘์€ ๊ฒฝ์šฐ ๋„ฃ๋Š”๋‹ค.
  2. top์— ์œ„์น˜ํ•œ ๊ฐ’์ด ๋” ์ž‘์œผ๋ฉด ํ•ด๋‹น ๊ฐ’์„ ๋ฐฐ๋‚ด๊ณ , k๋ฅผ ๊ฐ์†Œ์‹œํ‚จ๋‹ค.
  3. k๊ฐ€ 0์ด๋˜๋ฉด ๋‚จ์€ ๊ฐ’๋“ค์„ ์Šคํƒ์— ๋„ฃ๋Š”๋‹ค.
  4. ์Šคํƒ์ด ๊ฝ‰ ์ฐผ๋Š”๋ฐ, k๊ฐ€ ๋‚จ์•„์žˆ๋‹ค๋ฉด ๋งจ ์œ„์—์„œ k๊ฐœ๋ฅผ ๊บผ๋‚ธ๋‹ค.

๐Ÿ’ง Source Code

def solution(number, k):
    '''
    Notes:
        1. stack์— ๊ฐ’์ด ์—†๊ฑฐ๋‚˜, ๋” ์ž‘์€ ๊ฒฝ์šฐ ๋„ฃ๋Š”๋‹ค.
        2. top์— ์œ„์น˜ํ•œ ๊ฐ’์ด ๋” ์ž‘์œผ๋ฉด ํ•ด๋‹น ๊ฐ’์„ ๋นผ๋‚ด๊ณ , k๋ฅผ ๊ฐ์†Œ์‹œํ‚จ๋‹ค.
        3. k๊ฐ€ 0์ด๋˜๋ฉด ๋‚จ์€ ๊ฐ’๋“ค์„ ์Šคํƒ์— ๋„ฃ๋Š”๋‹ค.
        4. ์Šคํƒ์ด ๊ฝ‰ ์ฐผ๋Š”๋ฐ, k๊ฐ€ ๋‚จ์•„์žˆ๋‹ค๋ฉด ๋งจ ์œ„์—์„œ k๊ฐœ๋ฅผ ๊บผ๋‚ธ๋‹ค.

    Args:
        number (str) : ์ฃผ์–ด์ง„ ์ˆซ์ž (๋ฌธ์ž์—ด๋กœ ์ฃผ์–ด์ง)
        k (int) : ์‚ญ์ œํ•  ์ˆซ์ž ๊ฐœ์ˆ˜

    Returns:
        answer (str) : ์ „์ฒด์—์„œ k๊ฐœ๋ฅผ ์‚ญ์ œํ•œ ์ˆซ์ž ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’
    '''

    answer = ''
    stack = []

    for i,num in enumerate(number):
        while stack and stack[-1]<num and k>0:
            stack.pop()
            k -= 1

        if k==0:
            stack += number[i:]
            break

        stack.append(num)


    stack = stack[:-k] if k != 0 else stack
    answer = ''.join(stack)

    return answer

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