394. Decode String

re.sub create a new string, not in place modification 
class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        while '[' in s:
            s=re.sub(r'(\d+)\[([a-z]+)\]',lambda x:int(x.group(1))*x.group(2),s)
            
        return s
                 
my solution using stack
class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack=[]
        res=''
        tokens=iter(re.findall(r'\d+|\[|\]|[a-z]+',s))
        for token in tokens:
            if token.isdigit():
                stack.append(int(token))
                next(tokens) 
                
            else:
                if token==']':
                    temp=stack.pop()*stack.pop()
                else: 
                    temp=token
                if stack and not isinstance(stack[-1],int):
                    stack[-1]+=temp
                else:
                    stack.append(temp)
                
        if stack:
            res+=''.join(stack)
                
        return res
                    

你可能感兴趣的:(394. Decode String)