LeetCode/LeetCode75

[LeetCode 75] Medium - 394. Decode String

hyunkookim 2024. 11. 14. 16:40

394. Decode String

 

class Solution:
    def decodeString(self, s: str) -> str:
        dictionary = {']':'['}
        stack = []

        for w in s:
            if w != ']':
                stack.append(w)
            else:
                sub = ''
                while stack[-1] != '[':
                    sub = stack.pop() + sub # 왼쪽으로 string 추가해야하므로
                stack.pop()
            
                num_str = ''
                while stack and stack[-1].isdigit():
                    num_str = stack.pop() + num_str # 왼쪽으로 string 추가해야하므로
                stack.append(int(num_str)*sub)

        return ''.join(stack)