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].
Examples:
解法1: 递归
主要的想法就是, 每一个数字后面一定跟着一个左括号。 而左括号里面的东西是另外一个decode的过程,一个decode结束的标志是要么string结束了,或者是遇到了右括号([),
要注意的是,为了要不停的往前扫描,我们在递归函数返回的时候需要记录当前扫描到的位置. 可以用辅助class解决,在c++里也可以用引用解决这个问题.
C++
Java
解法2: Stack
用递归的算法如果要用iteration的办法解决一般会用到Stack. 基本的思路是用两个stack分别记录数字和字符, 当遇到”]”时使用当前栈顶的字母和数字来进行decode, 然后decode的结果要存入字母的栈顶.
最后的结果要么是当前的字符串, 要么是栈顶的字符串.
C++