LeetCode 题解工作台

字符串解码

给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string] ,表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,…

category

3

题型

code_blocks

3

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

class Solution: def decodeString(self, s: str) -> str:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

测试用例保证输出的长度不会超过 105

 

示例 1:

输入:s = "3[a]2[bc]"
输出:"aaabcbc"

示例 2:

输入:s = "3[a2[c]]"
输出:"accaccacc"

示例 3:

输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"

示例 4:

输入:s = "abc3[cd]xyz"
输出:"abccdcdcdxyz"

 

提示:

  • 1 <= s.length <= 30
  • s 由小写英文字母、数字和方括号 '[]' 组成
  • s 保证是一个 有效 的输入。
  • s 中所有整数的取值范围为 [1, 300] 
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
    def decodeString(self, s: str) -> str:
        s1, s2 = [], []
        num, res = 0, ''
        for c in s:
            if c.isdigit():
                num = num * 10 + int(c)
            elif c == '[':
                s1.append(num)
                s2.append(res)
                num, res = 0, ''
            elif c == ']':
                res = s2.pop() + res * s1.pop()
            else:
                res += c
        return res
speed

复杂度分析

指标
时间complexity is O(n * maxK) where maxK is the maximum repeat count, as each character can be processed multiple times. Space complexity is O(n) for stack usage in the iterative solution or recursion call stack in the recursive solution.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect the candidate to recognize nested repetition requires a stack or recursion.

  • question_mark

    Watch for mismanagement of multiple-digit repeat counts or nested brackets.

  • question_mark

    Look for concise handling of string concatenation to avoid repeated O(n^2) operations.

warning

常见陷阱

外企场景
  • error

    Confusing digits inside the encoded string with repeat counts, leading to incorrect expansion.

  • error

    Not correctly combining the previous string with repeated segments after popping from the stack.

  • error

    Failing to handle multiple nested brackets or multi-digit repeat numbers properly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allowing digits in the encoded string itself, requiring different parsing logic.

  • arrow_right_alt

    Limiting the maximum depth of nested brackets to test iterative versus recursive solutions.

  • arrow_right_alt

    Encoding with different delimiters or adding optional separators inside repeats.

help

常见问题

外企场景

字符串解码题解:栈·状态 | LeetCode #394 中等