python leetcode 394. Decode String
阿新 • • 發佈:2018-11-30
考察程式碼的編寫能力 棧和字串的操作
注意的地方是數字可能是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