1.题目
2.思路
由内向外的解析规则很符合栈的特性,对于内部的数字和字符串就借助辅助栈暂时的push和pop。
当 c 为]时,stack 出栈,拼接字符串 res = last_res + cur_multi * res,其中:
last_res是上个[到当前[的字符串,例如 “3[a2[c]]” 中的 a;
cur_multi是当前[到 ]内字符串的重复倍数,例如 “3[a2[c]]” 中的 2。
注意:list赋值给元素时是依次赋值,而非只有第一个元素得到整个list,当然这题append进去栈的也可以不是list,逐个元素append进去也行,pop出来的赋值就要对应好。
3.python代码
class Solution(object): def decodeString(self, s): stack, ans, multi = [], "", 0 for c in s: if '0' <= c <= '9': multi = multi * 10 + int(c) elif c == '[': stack.append([multi, ans]) ans, multi = "", 0 elif c == ']': TempMulti, LastAns = stack.pop() ans = LastAns + TempMulti * ans else: ans += c return ans
