Open HanchengZhao opened 7 years ago
class Solution(object):
def decodeString(self, s):
if not s:
return ""
stack = []
i = 0
digit = ""
while i < len(s):
if s[i].isdigit():
digit += s[i] # get the repetition number
i += 1
elif s[i] == "[":
stack.append([int(digit), i, len(digit)]) # save multiple times, index and digit string length
i += 1
digit = ""
elif s[i] == "]":
last = stack.pop()
s = s[:(last[1]-last[2])] + last[0] * s[(last[1]+1) : i] + s[(i+1):] # e.g. replace 2[abc] with abcabc
i += last[0] * (i-last[1]-1) - (i-last[1]+last[2]) # move the pointer accordingly
else:
i += 1
return s
The code is hard to read @HanchengZhao
Any comments will be nice.
Comments added
Thanks!
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].
*Example**