TikTok VO 面试真题解析:Decode String(栈 / 字符串解码)

15次阅读
没有评论

Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. k is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra spaces, and the brackets are well-formed.

Also, you may assume that the original data does not contain any digits, and that digits only represent repeat counts k, so inputs such as 3a or 2[4] will not appear.

Examples:

1. Input: s = "3[a]2[bc]"
   Output: "aaabcbc"

2. Input: s = "3[a2[c]]"
   Output: "accaccacc"

3. Input: s = "2[abc]3[cd]ef"
   Output: "abcabccdcdcdef"

4. Input: s = "abc3[cd]xyz"
   Output: "abccdcdcdxyz"

这是一道典型的字符串解码题,核心是处理嵌套结构 <code>k[encoded_string]</code>,将方括号中的内容重复 <code>k</code> 次并按顺序展开。由于题目允许多层嵌套,例如 <code>3[a2[c]]</code>,最自然的做法是用栈分别保存当前结果、重复次数和上一层字符串,遇到数字时累积倍数,遇到左括号时入栈切换上下文,遇到右括号时弹栈并拼接重复后的片段。这样可以在线性遍历中完成解析,兼顾嵌套深度和字符串拼接效率。

正文完
 0