美文网首页
394. Decode String

394. Decode String

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-13 13:05 被阅读0次
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

      本文链接:https://www.haomeiwen.com/subject/nszvmttx.html