利用两个栈记录嵌套的字符串和数字; 在遇到 "[" 时,将数字和当前字符串入栈 在遇到 "]" 时,将数字出栈与当前字符串相乘再加上字符串栈中的结果得到该层嵌套中的字符串,然后赋值给当前值
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @return string字符串
#
class Solution:
def decodeString(self , s: str) -> str:
# write code here
stack, digits, digit, cur = [], [], 0, ""
for c in s:
if "0" <= c <= "9":
digit += 10 * digit + int(c)
elif c == "[":
digits.append(digit)
digit = 0
stack.append(cur)
cur = ""
elif c == "]":
stack[-1] += cur * digits.pop()
cur = stack.pop()
else:
cur += c
return stack[-1] + cur if stack else cur