[LeetCode_394] Decode String(Python)

그냥·2024년 9월 23일
0

알고리즘

목록 보기
21/23

https://leetcode.com/problems/decode-string/description/?envType=study-plan-v2&envId=leetcode-75

문제


코드

class Solution:
    def decodeString(self, s: str) -> str:
        stk = []
        tmp = ''
        n = ''
        for i in s:
            if i.isdigit():
                n += i
            elif i == '[':
                stk.append(n)
                stk.append(i)
                n = ''
            elif i.isalpha():
                stk.append(i)
            else:
                while stk and stk[-1] != '[':
                    tmp = stk.pop() + tmp
                stk.pop()
                if stk and stk[-1].isdigit():
                    tmp = int(stk.pop()) * tmp
                stk.append(tmp)
                tmp = ''
        return ''.join(stk)
            

Idea

  • 숫자가 연속으로 나오는 경우 생각 -> 계속 더해 나가다가 '['가 나오면 stk에 넣고 초기화
  • ']'나오는 경우 -> '['이 나올때까지 stk값 pop -> 만약 stk[-1]가 숫자라면 tmp를 반복횟수만큼 곱해주고 다시 stk저장

0개의 댓글