LeetCode394 字符串解码

LeetCode394 字符串解码

栈模拟解码过程,栈顶记录当前子串(当前[]内字串)的重复次数和上一层(更外一层的[]内)该子串的前缀

class Solution:
    def decodeString(self, s: str) -> str:

        stack, ans, multi = [], '', 0

        for c in s:
            if c == '[':
                stack.append([multi, ans])
                ans, multi = '', 0
            elif c == ']':
                pre_multi, pre_ans = stack.pop()
                ans = pre_ans + pre_multi * ans
            elif ord(c) >= ord('0') and ord(c) <= ord('9'):
                multi = multi * 10 + int(c)
            else:
                ans += c
            
        return ans

posted on 2022-07-04 19:51  solvit  阅读(13)  评论(0编辑  收藏  举报

导航