Description:
Given an encoded string, return its 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; there are 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 will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 105.
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Solution: 100%, Step-by-Step Explaination with Pictures
The explaination of above link is really clear. All operation are focused on the left square bracket, we push two part into the stack. One is the number, which means the repeated times; the other is the string between the current left square bracket and the previous left square bracket.
Let's discuss 3[a2[c]]:
Before first '[', there are two parts: 3 and ' ', the stacks are : 3 and ' '.
Meet the second '[', the stacks are: 3,2 and ' ', 'a'
Now, current stringbuffer is 'c'
Meet the first ']', pop two stack, 2 and 'a', so 'a' + 2 * 'c' = acc
Meet the second ']', pop two stack, 3 and ' ', so ' ' + 3 * 'acc' = accaccacc
fun decodeString(s: String): String {
var sb = StringBuffer()
// repeat times
val stack = Stack<Int>()
// the string between current [ and front [
val stackStr = Stack<StringBuffer>()
var num = 0
s.forEach {
when (it) {
in '0'..'9' -> {
num = num * 10 + it.digitToInt()
}
// put number to number stack.
// put string between '[' and previous '[' to stringbuffer stack.
'[' -> {
stack.push(num)
num = 0
stackStr.push(sb)
sb = StringBuffer()
}
in 'a'..'z' -> {
sb.append(it)
}
']' -> {
// repeat times
var k = stack.pop()
val temp = sb
// the string between current '[' and front '['
sb = stackStr.pop()
// combine to a new sb
while (k-- > 0) {
sb.append(temp)
}
}
}
}
return sb.toString()
}