其他分享
首页 > 其他分享> > LeetCode394 字符串解码

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

标签:pre,multi,LeetCode394,解码,ans,字符串,ord,stack
来源: https://www.cnblogs.com/solvit/p/16444252.html