[LeetCode题解] 394. 字符串解码

题目链接: https://leetcode-cn.com/problems/decode-string/.
这道题是我在公司模拟自测的时候遇到的一道题。
参照题解区大佬的思路:

由于括号内嵌套括号,与栈的先进后出一致。

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack, multi, res = [], 0, ""
        #stack用于实现存储括号的嵌套关系
        #multi用于存储括号前的系数
        #res用于返回结果
        for c in s:
            if c == "[":
            	#当遇见左括号,用栈存储[系数,括号前的结果]
                stack.append([multi, res])
                multi, res = 0, ""
            elif c == "]":
            	#把整个括号内的结果取出
                curr_multi, curr_res = stack.pop(-1)
                res = curr_res + curr_multi * res 
            elif c.isnumeric():
                multi = multi * 10 + int(c)
            else:
                res += c
        return res
发布了10 篇原创文章 · 获赞 0 · 访问量 79

猜你喜欢

转载自blog.csdn.net/m0_46134602/article/details/104055689