|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(h), h is the depth of the recursion |
| 3 | + |
| 4 | +# Given an encoded string, return it's decoded string. |
| 5 | +# |
| 6 | +# The encoding rule is: k[encoded_string], |
| 7 | +# where the encoded_string inside the square brackets is |
| 8 | +# being repeated exactly k times. Note that k is guaranteed |
| 9 | +# to be a positive integer. |
| 10 | +# |
| 11 | +# You may assume that the input string is always valid; |
| 12 | +# No extra white spaces, square brackets are well-formed, etc. |
| 13 | +# |
| 14 | +# Furthermore, you may assume that the original data does not |
| 15 | +# contain any digits and that digits are only for those repeat numbers, k. |
| 16 | +# For example, there won't be input like 3a or 2[4]. |
| 17 | +# |
| 18 | +# Examples: |
| 19 | +# |
| 20 | +# s = "3[a]2[bc]", return "aaabcbc". |
| 21 | +# s = "3[a2[c]]", return "accaccacc". |
| 22 | +# s = "2[abc]3[cd]ef", return "abcabccdcdcdef". |
| 23 | + |
| 24 | +class Solution(object): |
| 25 | + def decodeString(self, s): |
| 26 | + """ |
| 27 | + :type s: str |
| 28 | + :rtype: str |
| 29 | + """ |
| 30 | + curr, nums, strs = [], [], [] |
| 31 | + n = 0 |
| 32 | + |
| 33 | + for c in s: |
| 34 | + if c.isdigit(): |
| 35 | + n = n * 10 + ord(c) - ord('0') |
| 36 | + elif c == '[': |
| 37 | + nums.append(n) |
| 38 | + n = 0 |
| 39 | + strs.append(curr) |
| 40 | + curr = [] |
| 41 | + elif c == ']': |
| 42 | + strs[-1].extend(curr * nums.pop()) |
| 43 | + curr = strs.pop() |
| 44 | + else: |
| 45 | + curr.append(c) |
| 46 | + |
| 47 | + return "".join(strs[-1]) if strs else "".join(curr) |
0 commit comments