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.
Example 1: Input: s = “3[a]2[bc]” Output: “aaabcbc”
Example 2: Input: s = “3[a2[c]]” Output: “accaccacc”
Example 3: Input: s = “2[abc]3[cd]ef” Output: “abcabccdcdcdef”
Constraints: 1 <= s.length <= 30 s consists of lowercase English letters, digits, and square brackets ‘[]’. s is guaranteed to be a valid input. All the integers in s are in the range [1, 300].
字符串解码。
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
/** * @param {string} s * @return {string} */ var decodeString = function (s) { // corner case if (s === null || s.length === 0) { return''; }
// normal case let numStack = []; let strStack = []; let res = ''; let len = s.length; for (let i = 0; i < len; i++) { let c = s.charAt(i); if (c === '[') { strStack.push(res); res = ''; } elseif (c == ']') { let num = numStack.pop(); let temp = strStack.pop(); for (let j = 0; j < num; j++) { temp += res; } res = temp; } elseif (!isNaN(c)) { let num = Number(c); while (i + 1 < len && !isNaN(s.charAt(i + 1))) { num = num * 10 + Number(s.charAt(i + 1)); i++; } numStack.push(num); } else { res += c; } } return res; };