394. Decode String #
Problem #
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; 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:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
Problem Summary #
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], which means the encoded_string inside the square brackets is 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 spaces in the input string, and the square brackets are always well-formed. Furthermore, you may assume that the original data does not contain digits, and all digits only represent the repeat count k. For example, inputs like 3a or 2[4] will not appear.
Solution Approach #
This problem is generally similar to Problem 880. Use a stack to process it. When encountering “[”, it means the string repetition is about to begin. In addition, the repeat number may have multiple digits, so we need to look backward to find the first character that is not a digit and convert the number. Finally, concatenate all the strings in the stack.
Code #
package leetcode
import (
"strconv"
)
func decodeString(s string) string {
stack, res := []string{}, ""
for _, str := range s {
if len(stack) == 0 || (len(stack) > 0 && str != ']') {
stack = append(stack, string(str))
} else {
tmp := ""
for stack[len(stack)-1] != "[" {
tmp = stack[len(stack)-1] + tmp
stack = stack[:len(stack)-1]
}
stack = stack[:len(stack)-1]
index, repeat := 0, ""
for index = len(stack) - 1; index >= 0; index-- {
if stack[index] >= "0" && stack[index] <= "9" {
repeat = stack[index] + repeat
} else {
break
}
}
nums, _ := strconv.Atoi(repeat)
copyTmp := tmp
for i := 0; i < nums-1; i++ {
tmp += copyTmp
}
for i := 0; i < len(repeat)-1; i++ {
stack = stack[:len(stack)-1]
}
stack[index+1] = tmp
}
}
for _, s := range stack {
res += s
}
return res
}