requirements

Given an encoded string, return its decoded string.

The encoding rule is k[encoded_string], indicating that the encoded_string inside the square brackets is repeated exactly K times. Note that k is guaranteed to be a positive integer.

You can assume that the input string is always valid; There are no extra Spaces in the input string, and the input square brackets are always formatted.

In addition, you can assume that the raw data does not contain numbers, and that all numbers represent only the number of repetitions k, such as no input like 3a or 2[4].

Example 1:

Input: s = "3[a]2[BC]" Output: "aaabcbc"Copy the code

Example 2:

Input: s = "3[a2[c]]" output: "accaccacc"Copy the code

Example 3:

Input: s = "2[ABC]3[CD]ef" Output: "abcabccdCDcdef"Copy the code

Example 4:

Input: s = abc3[CD]xyz output: "abccdcdcdxyz"Copy the code

The core code

class Solution:
    def decodeString(self, s: str) - >str:
        stack,res,count = [],"".0
        for c in s:
            if "0" <= c <= "9":
                count  = count * 10 + int(c)
            elif c == "[":
                stack.append([res,count])
                res,count = "".0
            elif c == "]":
                tmpRes,tmpCount = stack.pop()
                res = tmpRes + tmpCount * res
            else:
                res += c
        return res
Copy the code

Answer: This topic see know must use the stack to the solution, at the first glance, determines if the first number is the number, if there are Numbers, before is to carry forward, when we encounter [of Numbers and characters before, we will be stored in a stack, first to deal with the lining of the priority, behind when we encounter], explain the inner layer has been processed, We pop out the data that we’ve stored, do the outer processing, do a lot of concatenation, and finally get the string that we’ve decoded.