题目

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。k 保证为正整数

  1. 可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
  2. 可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a2[4] 的输入。

示例:

  1. s = "3[a]2[bc]", 返回 "aaabcbc".
  2. s = "3[a2[c]]", 返回 "accaccacc".
  3. s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".

方案一

def decodeString(s: str) -> str:
    if not s:
        return ""

    stack = []
    for c in s:
        if c != "]":
            stack.append(c)
            continue

        echo = []  # 需要重复的字符串
        while True:
            poped = stack.pop()
            if poped == "[":
                break
            echo.append(poped)
        echo.reverse()

        times = []  # 重复次数
        while True:
            if stack and stack[-1].isnumeric():
                times.append(stack.pop())
            else:
                break
        times = int(''.join(times[::-1]))
        stack.append(''.join(echo) * times)

    return "".join(stack)
  • 主要是利用栈的后入先出特性,匹配”[]”括号内的内容;
  • 为了避免使用 reverse 其实在拼接时候往字符串前面拼接就可以;

    leetcode 方案

class Solution:
    def decodeString(self, s: str) -> str:
        stack, res, multi = [], "", 0
        for c in s:
            if c == '[':
                stack.append([multi, res])
                res, multi = "", 0
            elif c == ']':
                cur_multi, last_res = stack.pop()
                res = last_res + cur_multi * res
            elif '0' <= c <= '9':
                multi = multi * 10 + int(c)            
            else:
                res += c
        return res

参考链接

https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/890/
https://leetcode-cn.com/problems/decode-string/solution/decode-string-fu-zhu-zhan-fa-di-gui-fa-by-jyd/