Share my Python Stack Simple Solution (Easy to understand)


  • 31
    A
    class Solution(object):
        def decodeString(self, s):
            stack = []
            stack.append(["", 1])
            num = ""
            for ch in s:
                if ch.isdigit():
                  num += ch
                elif ch == '[':
                    stack.append(["", int(num)])
                    num = ""
                elif ch == ']':
                    st, k = stack.pop()
                    stack[-1][0] += st*k
                else:
                    stack[-1][0] += ch
            return stack[0][0]
    

  • 0
    T

    almost the same

        def decodeString(self, s):
            """
            :type s: str
            :rtype: str
            """
            stack, i, n = [[1, '']], 0, len(s)
            while i < n:
                c = s[i]
                if 'a' <= c <= 'z':
                    stack[-1][1] += c
                elif '0' <= c <= '9':
                    j = i
                    while '0' <= s[j] <= '9':
                        j += 1
                    stack += [int(s[i:j]), ''],
                    i = j
                elif c == ']':
                    j, t = stack.pop()
                    stack[-1][1] += t * j
                else:
                    stack[-1][1] += c
                i += 1
            return stack[0][1]
    

  • 1

    @ayushpatwari Why ''.join([st]*k) instead of just st * k?


  • 0
    A

    @StefanPochmann well honestly I didn't know I could do that (I am just starting to get a hang of python syntactic sugar). I have edited the post now :)


  • 0

    @StefanPochmann May I ask a question? Since string type is immutable in Python, would it save more memory if we do:

    tmp, i = [], 0
    while i<k:
        tmp=tmp.append(''.join(st))
    

    instead of st*k?


  • 0
    W

    nice codes! thank you !


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.