Leetcode: Decode String

Decode String

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].


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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

## Blog link: https://code.dennyzhang.com/decode-string
## Basic Ideas: Use stack
##              number applies to the next string
##              Keep pushing until we get a ']', then we pop
##              Keep poping until we get a '['. Caculate the result and push again. 
##                             Then check the next element in the input string.
##   Watch out: 12[a]2[bc]
## Complexity:
class Solution(object):
    def decodeString(self, s):
        :type s: str
        :rtype: str
        stack = []
        prev_str = ''
        for ch in s:
            if ch == '[':
                if prev_str != '':
                    prev_str = ''
            elif ch == ']':
                element = prev_str
                prev_str = ''
                # pop until we get '['
                while stack[-1] != '[':
                    v = stack.pop()
                    if v.isdigit():
                        element = element*int(v)
                        element = "%s%s" % (v, element)
                stack.pop() # remove [
                while len(stack)!= 0 and stack[-1].isdigit():
                    element = element*int(stack.pop())
            elif ch.isalpha():
                if prev_str != '' and prev_str.isdigit():
                    prev_str = ''
                prev_str = '%s%s' % (prev_str, ch)
                if prev_str != '' and prev_str.isalpha():
                    prev_str = ''
                prev_str = '%s%s' % (prev_str, ch)
            # print stack

        if prev_str != '': stack.append(prev_str)
        return ''.join(stack)

Share It, If You Like It.

Leave a Reply

Your email address will not be published.