[LeetCode explanations] 394. The decoded string

Topic links: https://leetcode-cn.com/problems/decode-string/ .
This question is a question I encountered at the time of the company's self-test simulation.
Reference solution to a problem area Gangster ideas:

Because nested parentheses within parentheses, and advanced post-stack consistent.

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
Published 10 original articles · won praise 0 · Views 79

Guess you like

Origin blog.csdn.net/m0_46134602/article/details/104055689