394. Decode String
题目描述
Given an encoded string, return it’s decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].
示例:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
解答
这道题的思路是从字符串的开头往后面读,当读到数字的时候,就把数字存起来,当读到字符串的时候,把字符串存起来,然后把数字 * 字符串 个数的字符存到最终字符串里面。
当遇到[ 的时候,就进行递归,把上面的步骤再执行一遍,遇到 ]时结束递归,返回递归内得到的字符串,然后把递归内得到的字符串拼接到最终字符串里面。
具体代码如下。
代码
1 | class Solution { |