python leetcode 394. Decode String

考察代码的编写能力 栈和字符串的操作
注意的地方是数字可能是111这样的大于10的数字
字母要考虑大小写
左右括号要对应

class Solution:
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        base = []
        s1=[]
        
        i=0
        res=''
        while i<len(s):
            
            if '1' <= s[i] and '9'>= s[i]:
                index=i
                while i+1<len(s) and '0' <= s[i+1] and '9'>= s[i+1]:
                    i+=1
                base.append(int(s[index:i+1]))
                
            elif s[i] =='[':
                s1.append('[')
            elif ('a' <= s[i] and 'z'>= s[i]) or ('A' <= s[i] and 'Z'>= s[i]):
                tempstr=s[i]
                index=i
                while i+1<len(s) and (('a' <= s[i+1] and 'z'>= s[i+1]) or ('A' <= s[i+1] and 'Z'>= s[i+1])):
                    tempstr+=s[i+1]
                    i+=1
                
                s1.append(tempstr)
                
                    
            elif s[i] ==']':
                temp=''
                
                b1 = base.pop()
                while s1[-1]!='[':
                    temp=s1.pop() + temp
                tstr = b1*temp
                s1.pop()
                while len(s1) >0 and s1[-1]!='[':
                    tstr=s1.pop() + tstr
                s1.append(tstr) 
                
            i+=1
        while len(s1)>0:
            res =s1.pop()+res
        return res

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84585304
今日推荐