HanchengZhao / algorithm-notes

0 stars 0 forks source link

394. Decode String (following yesterday's question) #7

Open HanchengZhao opened 7 years ago

HanchengZhao commented 7 years ago

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**

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
HanchengZhao commented 7 years ago

using stack

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
YeWang0 commented 7 years ago

The code is hard to read @HanchengZhao

YeWang0 commented 7 years ago

Any comments will be nice.

HanchengZhao commented 7 years ago

Comments added

YeWang0 commented 7 years ago

Thanks!