λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

Algorithm/ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€

[ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€] ν‘œ νŽΈμ§‘ (Python)

1. 문제 μ„€λͺ…

문제 링크

  • μž…λ ₯
    • n : 처음 ν‘œμ˜ ν–‰ 개수λ₯Ό λ‚˜νƒ€λ‚΄λŠ” μ •μˆ˜
    • k : μ²˜μŒμ— μ„ νƒλœ ν–‰μ˜ μœ„μΉ˜λ₯Ό λ‚˜νƒ€λ‚΄λŠ” μ •μˆ˜
  • 좜λ ₯
    • μˆ˜ν–‰ν•œ λͺ…령어듀이 λ‹΄κΈ΄ λ¬Έμžμ—΄ λ°°μ—΄ cmdκ°€ λ§€κ°œλ³€μˆ˜λ‘œ μ£Όμ–΄μ§ˆ λ•Œ, λͺ¨λ“  λͺ…λ Ήμ–΄λ₯Ό μˆ˜ν–‰ν•œ ν›„ ν‘œμ˜ μƒνƒœμ™€ 처음 주어진 ν‘œμ˜ μƒνƒœλ₯Ό λΉ„κ΅ν•˜μ—¬ μ‚­μ œλ˜μ§€ μ•Šμ€ 행은 O, μ‚­μ œλœ 행은 X둜 ν‘œμ‹œν•˜μ—¬ λ¬Έμžμ—΄ ν˜•νƒœλ‘œ return

2. μ½”λ“œ

solution1.py

class Node:
    def __init__(self):
        self.removed = False
        self.prev = None
        self.next = None

def solution(n, k, cmd):
    nodeArr = [Node() for _ in range(n)]
    for i in range(1, n):
        nodeArr[i-1].next = nodeArr[i]
        nodeArr[i].prev = nodeArr[i-1]

    curr = nodeArr[k]
    mystack = []

    for str in cmd:
        if str[0] == 'U':
            x = int(str[2:])
            for _ in range(x):
                curr = curr.prev
        elif str[0] == 'D':
            x = int(str[2:])
            for _ in range(x):
                curr = curr.next
        elif str[0] == 'C':
            mystack.append(curr)
            curr.removed = True
            up = curr.prev
            down = curr.next
            if up:
                up.next = down #μ—°κ²°
            if down:
                down.prev = up#μ—°κ²°
                curr = down
            else:#λ§ˆμ§€λ§‰ 값이면
                curr = up
        else: #Z
            node = mystack.pop()
            node.removed = False
            up = node.prev
            down = node.next
            if up:
                up.next = node
            if down:
                down.prev = node


    answer = ''
    for i in range(n):
        if nodeArr[i].removed: #True
            answer+='X'
        else:
            answer+='O'
    return answer

3. 회고

  • μ²˜μŒμ—λŠ” 자료ꡬ쑰λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  ν’€λ €κ³  ν•˜λ‹€λ³΄λ‹ˆ 계속 λ§‰ν˜”λ‹€.
  • 풀이λ₯Ό λ³΄λ‹ˆ, μ—°κ²°λ¦¬μŠ€νŠΈλ₯Ό ν™œμš©ν•΄ ν’€μ—ˆλ‹€.
  • class둜 Node 객체λ₯Ό μ„ μ–Έν•΄μ„œ 전후정보λ₯Ό μ—…λ°μ΄νŠΈν•  수 있고, μ‚­μ œν•œ ν›„ ν˜„μž¬ μœ„μΉ˜λ₯Ό μ—…λ°μ΄νŠΈν•˜κΈ° νŽΈν–ˆλ‹€.
    • μ‚­μ œ ν›„μ—λŠ” ν˜„μž¬ μœ„μΉ˜κ°€ μ•„λž˜λ‘œ λ‚΄λ €κ°€λŠ”λ°, λ§ˆμ§€λ§‰ λ…Έλ“œκ°€ μ‚­μ œλ  λ•ŒλŠ” ν˜„μž¬μœ„μΉ˜λ₯Ό μœ„λ‘œ μ˜¬λ €μ•Όν•œλ‹€.
  • μ—°κ²°λ¦¬μŠ€νŠΈλ₯Ό νŒŒμ΄μ¬μ—μ„œ κ΅¬ν˜„ν•˜λŠ” 방법을 λ°°μ› κ³  μž¬λ―Έμžˆμ—ˆλ‹€.
  • λ‹€μŒ λ²ˆμ—λ„ ν™œμš©ν•  수 μžˆλ„λ‘ κ΅¬ν˜„μ—°μŠ΅μ„ ν•΄μ•Όκ² λ‹€.

4. μ°Έκ³ 

https://www.youtube.com/watch?v=A-KfaMVBfhg